1

我正在尝试制作一个 Web 应用程序,让用户在 html 画布上插入小字符图像。计划是让用户单击虚拟键盘上的按钮,然后在画布上单击以使相应的字符出现在用户单击的任何位置。现在我只是想让一个图像在点击时出现在画布上,但到目前为止它没有做任何事情。这是我现在拥有的代码,它嵌入在 html 文件中。

<script type="text/javascript">
            var mathCanvas = document.getElementById("matharea");
            var ctx = mathCanvas.getContext("2d");
            var el = mathCanvas;
            var xPos = 0;
            var yPos = 0;
            while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)){
                xPos += el.offsetLeft - el.scrollLeft;
                yPos += el.offsetTop - el.scrollTop;
                el = el.parentNode;
            }
            var img = new Image();
            img.src = "five.png";
            mathCanvas.onclick = function(event){
                var x = event.clientX - xPos;
                var y = event.clientY - yPos;
                ctx.drawImage(img,x,y);
            };
</script>

我已经测试了 onclick 事件,它返回坐标,但图像不会出现。这里出了什么问题?

4

1 回答 1

3

This should work since the click event will be firing on the canvas itself:

        var mathCanvas = document.getElementById("matharea");
        var ctx = mathCanvas.getContext("2d");

        var img = new Image();
        img.src = "five.png";
        mathCanvas.onclick = function(event){
            var x = event.offsetX;
            var y = event.offsetY;
            ctx.drawImage(img,x,y);
        };

To center the image on the point:

        var mathCanvas = document.getElementById("matharea");
        var ctx = mathCanvas.getContext("2d");

        var img = new Image();
        img.src = "five.png";
        mathCanvas.onclick = function(event){
            var x = Math.round(event.offsetX - img.width/2);
            var y = Math.round(event.offsetY - img.height/2);
            ctx.drawImage(img,x,y);
        };
于 2012-11-05T21:26:58.050 回答