在mouseclick上在画布上绘制一个实心圆 [英] Drawing a filled circle in a canvas on mouseclick

查看:94
本文介绍了在mouseclick上在画布上绘制一个实心圆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过鼠标单击在画布上绘制一个实心(或不实心)圆圈,但是我无法使我的代码正常工作,我已经做了很多尝试!

I want to draw a filled (or not filled) circle in a canvas on mouseclick, but I can't get my code to work properly, I've tried pretty much everything!

这是我的HTML:

<div id="images"></div>
<canvas style="margin:0;padding:0;position:relative;left:50px;top:50px;" id="imgCanvas" width="250" height="250" onclick="draw(e)"></canvas>

和我当前的脚本:

var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

function createImageOnCanvas(imageId) {
    canvas.style.display = "block";
    document.getElementById("images").style.overflowY = "hidden";
    var img = new Image(300, 300);
    img.src = document.getElementById(imageId).src;
    context.drawImage(img, (0), (0)); //onload....
}

function draw(e) {
    var pos = getMousePos(canvas, e);
    posx = pos.x;
    posy = pos.y;
    context.fillStyle = "#000000";
    context.arc(posx, posy, 50, 0, 2 * Math.PI);
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

当且仅当我删除"use strict"时,该代码才能正常工作;但是在此作业中,我必须编写一个即使使用也可以使用的代码,这是我的问题.

The code works just fine if and only if I remove the "use strict";, but in this assignment I have to make a code that works even with it, which is my problem.

这是 jsFiddle

推荐答案

我自己解决了.

function draw(e) {

    var canvas = document.getElementById("imgCanvas");
    var context = canvas.getContext("2d");
    var rect = canvas.getBoundingClientRect();
    var posx = e.clientX - rect.left;
    var posy = e.clientY - rect.top;

    context.fillStyle = "#000000";
    context.beginPath();
    context.arc(posx, posy, 50, 0, 2 * Math.PI);
    context.fill();
}

此脚本对我来说很好.

这篇关于在mouseclick上在画布上绘制一个实心圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆