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

我正在画布中用for循环生成5个圆,我想给它们一个类,以便可以用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),但是没有用.

这是一个在线资源的链接,所以你们可以检查一下= LINK

解决方法:

您的代码有很多错误.

您试图将属性添加到数组中的字符串中是不可能的.使用点或括号符号将属性添加到对象.

点表示法

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中.您真正做错的就是尝试将属性添加到数组值,错误的代码处理技巧和方法.宽度,高度之前的样式.注意只能将className的width和height属性添加到DOM元素.

现在,您可以通过for循环和circles数组,或通过将nth-child选择器与CSS一起使用来访问各个圆圈.例如.circle:nth-​​child(1){动画/过渡}

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%;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。