将类添加到画布元素HTML5和CreateJS

Add class to canvas element HTML5 & CreateJS

本文关键字:元素 HTML5 CreateJS 添加 布元素      更新时间:2023-09-26

我在画布中生成了 5 个带有 for 循环的圆圈,我想给它们一个类,以便我可以用 jquery 控制它们,但我做错了什么。你们能弄清楚发生了什么吗?

var stage;
var quantity = 6,
    width = 60,
    height = 60,
    circles = [];
function init(){
    stage = new createjs.Stage("myCanvas");
    stage.width = 500;
    stage.height = 600;
    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener("tick", onTick);
    setupGame();
}
function setupGame() {
    for(var i = 0; i < quantity; i++) {   
         var circle = document.createElement("img");
         circle.setAttribute('src', 'images/circles/circle'+i+'.png');
         circle.className = "circle";
         circle.style.position = "absolute";
         circle.style.left = Math.floor((Math.random() * 100)) + "%";
         circle.style.top = Math.floor((Math.random() * 100)) + "%";
         circle.style.width = width + "px";
         circle.style.height = height + "px";
         document.body.appendChild(circle);
         circles.push(circle);
    }
}
function onTick(e){
    stage.update(e);
}

新版本。在JonnyD的帮助下,我现在有一个功能循环。唯一的问题是图像被附加到身体上,而不是我的舞台上。我已经尝试过stage.appendChild(circle),但它不起作用。

这是在线资源的链接,因此你们可以查看= 链接

你的代码有很多问题。

您正在尝试向数组中的字符串添加属性,这是不可能的。属性使用点或括号表示法添加到对象中。

点表示法

foo.bar.baz

方括号表示法

foo['bar']['baz']

我认为您要做的是在"屏幕"或技术上更正确的 DOM (https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) 上随机位置创建五个圆圈,将 H&W 设置为 60px,类名为 myClass。

我已经为您重写了代码,如果您愿意,您可以删除样式javascript行并将它们添加到CSS中。您真正做错的只是尝试向数组值添加属性,错误的代码技术以及在宽度,高度之前缺少.style。注意您只将类名以及宽度和高度属性添加到 DOM 元素。

现在,您可以通过 for 循环和圆圈数组或使用带有 CSS 的第 n 个子选择器来访问各个圆圈。例如 .circle:nth-child(1) {animation/transition}

var quantity = 5,
    width = 60,
    height = 60
    circles = [];
function setUp() {
    for(var i = 0; i < quantity; i++) {   
         var circle = document.createElement("div");
         circle.className = "circle";
         circle.style.position = "absolute";
         circle.style.left = Math.floor((Math.random() * 100)) + "%";
         circle.style.top = Math.floor((Math.random() * 100)) + "%";
         circle.style.backgroundColor = "black";
         circle.style.width = width + "px";
         circle.style.height = height + "px";
         circles.push(circle);
         document.body.appendChild(circle);
    }
}
setUp();
.circle {
  border-radius: 50%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
}

我没有看到你在使用CreateJS..在这种情况下使用这样的符号是可以的。

var circle = new createjs.Shape();
circle.graphics.beginFill("DeepSkyBlue").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);

确保同时更新阶段。

stage.update();

我意识到这个问题已经得到了回答,但是由于我单击它试图找出如何在jquery中向canvas对象添加类,我将发布如何做到这一点。

var thing = canvas_object;
$('body').append(thing);
var canvas = $('canvas');
canvas.addClass('test');

画布内的东西不在 DOM 中,但可缩放矢量图形图像中的元素在中,并且可以通过这种方式进行操作。

如果方便,请尝试使用 SVG.svg.js 是一个用于操作 SVG 的轻量级库。