如何将html 5画布的背景图像设置为.png图像 [英] How to set the background image of a html 5 canvas to .png image
问题描述
我想知道如何将画布的背景图片设置为.png文件。我不想在画布的背面添加图像,使画布透明。
I would like to know how it is possible to set the background image of a canvas to a .png file. I do not want to add the image in the back of the canvas and make the canvas transparent.
我想让用户能够在画布上绘制背景为.png的图片,以便我以后可以将其作为.png提取
I want the user to be able to actually draw on that canvas with the background being the .png image so that I can extract it later as a .png with the drawings that the user made.
推荐答案
如这个例子,你可以通过CSS应用背景到 canvas
元素,这个背景不会被视为图像的一部分,例如通过 toDataURL()
获取内容。
As shown in this example, you can apply a background to a canvas
element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL()
.
这里是内容的例子,Stack Overflow后代:
Here are the contents of the example, for Stack Overflow posterity:
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>Canvas Background through CSS</title>
<style type="text/css" media="screen">
canvas, img { display:block; margin:1em auto; border:1px solid black; }
canvas { background:url(lotsalasers.jpg) }
</style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#f00';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.strokeRect(140,60,40,40);
var img = document.getElementsByTagName('img')[0];
img.src = can.toDataURL();
</script>
</body></html>
这篇关于如何将html 5画布的背景图像设置为.png图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!