【问题标题】:Set attributes of HTML canvas arc设置 HTML 画布弧的属性
【发布时间】:2010-12-27 05:24:23
【问题描述】:

我还是 HTML5 和画布的新手。我正在画布上设置点:

var ctx = canvas.getContext("2d");
        for (var i = 0; i < 500; i++) {
            ctx.fillStyle = 'rgba(255,255,255,0.2)';
            ctx.beginPath();
            ctx.arc(points[i].x, points[i].y, radius, 0, Math.PI * 2, true);
            ctx.fill();
        }

有没有一种方法,一旦画布被绘制,当我寻找说“200”时,我可以识别特定的点并改变它的颜色?还是重新绘制整个画布会更好?

【问题讨论】:

  • 请注意,保留绘图模式系统(如 HTML 或 SVG)维护与绘制元素相关的特定对象,非保留绘图模式 系统——如 HTML Canvas——没有。使用 SVG,您可以在特定元素上注册事件处理程序;使用 HTML Canvas,您必须自己跟踪所有对象和位置,并根据自己的命中检测代码跟踪事件。

标签: javascript html canvas


【解决方案1】:
var canvas, ctx, points;
var radius = 10;
var num = 20;
$(function () {
    points = [];
    for (var i = 0; i < num; i++) {
        points.push({
            x: Math.random() * 300 >> 0,
            y: Math.random() * 200 >> 0
        });
    }
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext("2d");
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, 300, 200);

    for (var i in points) {
        ctx.fillStyle = 'rgba(255,255,255,0.8)';
        ctx.beginPath();
        ctx.arc(points[i].x, points[i].y, radius, 0, Math.PI * 2, true);
        ctx.fill();
    }
});

var initrand = Math.random() * num >> 0;

function change() {
    var random = initrand;
    ctx.fillStyle = '#234263';
    ctx.beginPath();
    ctx.arc(points[random].x, points[random].y, radius, 0, Math.PI * 2, true);
    ctx.fill();
    initrand = Math.random() * num >> 0;
}

Demo for above Code

【讨论】:

  • 你不能被打败!谢谢!
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 2011-09-04
  • 2012-01-22
相关资源
最近更新 更多