Javascript 如何在画布上使用背景图像?
我找到了这个密码Javascript 如何在画布上使用背景图像?,javascript,canvas,Javascript,Canvas,我找到了这个密码 http://jsfiddle.net/dtrooper/AceJJ/ 我试图在画布上添加一个背景图像(这样它就不会是黑色的) 我已将这些行添加到$(document).ready函数中 var background = new Image(); background.src = url("img/header.jpg"); 但我得到的只是未破坏的语法错误:意外标记非法 我还想在背景上加上文字(比如说“欢迎新年”+新行+“祝你平安,好运” 谢谢试试这个: var img =
http://jsfiddle.net/dtrooper/AceJJ/
我试图在画布上添加一个背景图像(这样它就不会是黑色的)
我已将这些行添加到$(document).ready函数中
var background = new Image();
background.src = url("img/header.jpg");
但我得到的只是未破坏的语法错误:意外标记非法
我还想在背景上加上文字(比如说“欢迎新年”+新行+“祝你平安,好运”
谢谢试试这个:
var img = new Image();
img.src = "http://imgurl.com";
url()用于CSS中。jsiddle:
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.src = "http://imagesci.com/img/2013/03/cute-christmas-dogs-8313-hd-wallpapers.jpg";
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.font = '40pt Calibri';
ctx.fillStyle = 'red';
ctx.fillText("Welcome to the new year", 250, 100);
ctx.fillText("Be safe and good luck", 350, 600);
}
您必须创建一个新的Image
变量,然后访问其属性src
,该属性是图像的源。因此,您首先创建一个新的图像
并提供源。然后我们必须先等待图像加载。加载图像后,我们通过drawImage
将其呈现到画布上,然后我们继续并进行d使用fillText
函数来绘制一些文本
您将必须解决如何正确居中文本和更改图像,但我提供的代码应该可以帮助您开始:)
更新
jsFiddle:
只需在循环函数中渲染图像和文本,但是正如我前面所述,您需要找出渲染图像和文本的最佳方法
另一个更新
jsFiddle:
要在图像上绘制焰火轨迹,只需在火箭渲染时创建粒子即可
// ... near the end of the Rocket.prototype.render function
c.fill();
c.restore();
var particle = new Particle(this.pos);
particle.size = 10;
particle.gravity = 0.2;
particle.resistance = 0.92;
particle.shrink = Math.random() * 0.05 + 0.93;
particle.flick = true;
particle.color = this.explosionColor;
particles.push(particle);
};
在循环函数中更改以下内容:
// clear canvas
context.fillStyle = "rgba(0, 0, 0, 0.05)";
context.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
为此:
context.save();
if (first) { // only the first time you draw the full image
first = false;
context.globalAlpha = 1;
} else {
context.globalAlpha = 0.2; // <--- PLAY WITH THIS FOR BETTER EFFECT
}
context.drawImage(img, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
context.restore()
// clear canvas
//context.fillStyle = "rgba(0, 0, 0, 0.05)";
//context.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
不是完美的,但从这里你可以找到你的解决方案
例如:
为什么要调用
url
?您定义了该函数吗?这样我就可以设置背景图像您在哪里定义了函数url
?请出示完整的代码。您在问题中显示的代码不在您的JSFIDLE中。为什么不只是:background.src=“img/header.jpg”
?您也可以使用CSS或style
属性将图像设置为背景图像。当我将此放置在document.ready中时,添加此内容后,图像会淡入黑色,图像和文本淡入黑色,烟花在黑色背景上绽放
context.save();
if (first) { // only the first time you draw the full image
first = false;
context.globalAlpha = 1;
} else {
context.globalAlpha = 0.2; // <--- PLAY WITH THIS FOR BETTER EFFECT
}
context.drawImage(img, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
context.restore()
// clear canvas
//context.fillStyle = "rgba(0, 0, 0, 0.05)";
//context.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
var img = new Image();
var first = true;
img.src = "YOUR_IMAGE_URL";