2

我想知道是否有人可以帮助我弄清楚如何使用 HTML5 Canvas 和 JavaScript 在图像上绘制对象?

我写了一个例子来说明我的问题(只要你有一个名为 choc.jpg 的图像可用,它应该可以工作)。我希望香蕉对象出现在 JPEG 上,但事实并非如此。我是 HTML5 和画布的新手,非常感谢您指出正确的方向。非常感谢你的帮助!

<!DOCTYPE HTML>
<script>

window.onload=function() {
var testcanvas=document.getElementById("bananaDesign");
var testcontext=testcanvas.getContext('2d');

//set a background image
/* if I comment out this section no image appears and the banana gets drawn. How do I get banana to go over image? */

var importedImg = new Image();
importedImg.src = 'pictures/choc.JPG';
importedImg.onload = function(){
testcontext.drawImage(importedImg, 10, 10);
};


//draw a banana
testcontext.fillStyle = "#FFA824";
testcontext.beginPath();
testcontext.moveTo(62,20);
testcontext.lineTo(80,20); //2
testcontext.lineTo(80,30); //3
testcontext.lineTo(90,50); //4
testcontext.lineTo(80,85); //5
testcontext.lineTo(45,95); //6
testcontext.lineTo(40,80); //7
testcontext.lineTo(60,60); //8
testcontext.lineTo(60,30); //9
testcontext.fill();
}

</script>


<canvas id="bananaDesign" width="500" height="600" style="border: 5px red solid">
<p>Your browser does not display HTML5 canvas. Please update to view this design.</p>
</canvas>
4

2 回答 2

1

您需要在上下文中配置globalCompositeOperation属性。在您的情况下,将值设置为'destination-over'以绘制图像。这是所有可能值的列表http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-globalcompositeoperation

您的代码示例http://jsfiddle.net/gU4xc/

于 2012-10-18T08:44:29.863 回答
1

图像是异步加载的,因此在您绘制香蕉(因此在其上方)之后,它实际上被绘制到画布上。一个快速的解决方法是将你的香蕉绘制代码移动到你的图像加载处理程序中,在你将图像绘制到画布之后(参见http://jsfiddle.net/5pGqV/,回想起来我选择的背景图像并不理想;)):

<!DOCTYPE HTML>
<script>

    window.onload=function() {
        var testcanvas=document.getElementById("bananaDesign");
        var testcontext=testcanvas.getContext('2d');

        //set a background image
        /* if I comment out this section no image appears and the banana gets drawn. How do I get banana to go over image? */

        var importedImg = new Image();
        importedImg.src = 'pictures/choc.JPG';
        importedImg.onload = function(){

            //draw the loaded image to canvas first
            testcontext.drawImage(importedImg, 10, 10);

            //now draw a banana on top
            testcontext.fillStyle = "#FFA824";
            testcontext.beginPath();
            testcontext.moveTo(62,20);
            testcontext.lineTo(80,20); //2
            testcontext.lineTo(80,30); //3
            testcontext.lineTo(90,50); //4
            testcontext.lineTo(80,85); //5
            testcontext.lineTo(45,95); //6
            testcontext.lineTo(40,80); //7
            testcontext.lineTo(60,60); //8
            testcontext.lineTo(60,30); //9
            testcontext.fill();
        }; 
    }

</script>


<canvas id="bananaDesign" width="500" height="600" style="border: 5px red solid">
<p>Your browser does not display HTML5 canvas. Please update to view this design.</p>
</canvas>
于 2012-10-18T08:41:00.547 回答