繁体   English   中英

如何在画布上使用背景图像?

[英]How can I use a background image on a canvas?

我找到了这个代码

http://jsfiddle.net/dtrooper/AceJJ/

我正在尝试向画布添加背景图像(因此它不会是黑色的)。

我已将这些行添加到 $(document).ready 函数中

var background = new Image();
background.src = url("img/header.jpg");

但我得到的只是Uncaught SyntaxError: Unexpected token ILLEGAL

我还想在背景上添加文字(说“欢迎来到新的一年”+ NewLine +“注意安全,祝你好运”

谢谢你

在循环函数中改变这个:

// 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);

在循环函数外添加以下内容:

var img = new Image();
var first = true;
img.src = "YOUR_IMAGE_URL";

并不完美,但从这里您可以找到您的解决方案。

例子: http : //jsfiddle.net/AceJJ/1748/

jsFiddle: https ://jsfiddle.net/CanvasCode/6ju8acro/1/

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 ,它是图像的来源。 所以你首先创建一个新的Image提供一个源。 然后我们必须首先等待图像加载。 图像加载drawImage ,我们通过drawImage将其渲染到画布上,然后我们继续使用fillText函数绘制一些文本。

您必须弄清楚如何正确居中文本并更改图像,但我提供的代码应该可以帮助您入门:)

更新

jsFiddle: http : //jsfiddle.net/CanvasCode/AceJJ/1743/

// clear canvas
// Render background and text first
context.drawImage(img, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
context.font = '40pt Calibri';
context.fillStyle = 'red';
context.fillText("Welcome to the new year", 150, 100);
context.fillText("Be safe and good luck", 250, 600);
//context.fillStyle = "rgba(0, 0, 0, 0.05)";
//context.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

只需在循环函数中渲染图像和文本,但是如上所述,您需要找出渲染图像和文本的最佳方式

另一个更新

jsFiddle: http : //jsfiddle.net/CanvasCode/AceJJ/1756/

要在图像上绘制烟花轨迹,只需在像这样渲染火箭时创建粒子

  // ... 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);
};

尝试这个 :

var img = new Image();
img.src = "http://imgurl.com";

url() 在 CSS 中使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM