簡體   English   中英

將類添加到畫布元素 HTML5 和 CreateJS

[英]Add class to canvas element 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 數組使用帶有 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();

畫布內的東西不在 DOM 中,但可縮放矢量圖形圖像中的元素在,並且可以通過這種方式進行操作。

如果方便,請嘗試使用 SVG。 svg.js是一個用於操作 SVG 的輕量級庫。

我意識到這個問題已經得到解答,但是因為我點擊了這個試圖找出如何在 jquery 中向畫布對象添加一個類,我將發布如何做到這一點。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM