[英]Fade out effect for line in HTML5 canvas with background image
我目前正在研究一个HTML画布示例,该示例在画布上绘制后会淡出一条线,尽管我的问题是:如何在使用背景图像时实现这一点?
现场演示 (本文底部链接中的当前代码)
CSS:
canvas {
background-image: url("https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2018/02/PluralsightandSO.jpg");
background-size: 100% 100%;
}
JavaScript的:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
painting = false,
lastX = 0,
lastY = 0;
canvas.width = canvas.height = 600;
canvas.onmousedown = function (e) {
if (!painting) {
painting = true;
} else {
painting = false;
}
lastX = e.pageX - this.offsetLeft;
lastY = e.pageY - this.offsetTop;
};
canvas.onmousemove = function (e) {
if (painting) {
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
lastX = mouseX;
lastY = mouseY;
}
}
function fadeOut() {
ctx.fillStyle = "rgba(255,255,255,0.3)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
setTimeout(fadeOut,100);
}
fadeOut();
我意识到fillRect
用fillStyle
填充了整个画布,所以我假设我可以将图像添加到画布上,但是如您所知,通过使用以下代码,动画是不同的:
var image = new Image();
image.src = "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2018/02/PluralsightandSO.jpg"
ctx.drawImage(image, 0, 0);
当前的Live Demo (经过上述更改)-过于僵化,没有那么长的尾巴
有什么想法吗?
您正在绘制30%的透明正方形以获得“褪色”效果:
ctx.fillStyle = "rgba(255,255,255,0.3)";
因此,您还需要透明地绘制PNG
canvas.onmousemove = function (e) {
if (painting) {
// set line alpha to 1
ctx.globalAlpha = 1.0;
// your paint code here
}
}
function fadeOut() {
var image = new Image();
// set image alpha to 0.3
ctx.globalAlpha = 0.3;
// your draw image code here
}
顺便说一句,您不需要每次都创建新图像!
您需要指定宽度和高度:
ctx.drawImage(image, 0, 0, 600, 600);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.