我正在尝试在另一个画布上添加一个画布——我怎样才能让这个功能等到第一个画布创建完成?
function PaintObject(brush) { this.started = false; // get handle of the main canvas, as a DOM object, not as a jQuery Object. Context is unfortunately not yet // available in jquery canvas wrapper object. var mainCanvas = $("#" + brush).get(0); // Check if everything is ok if (!mainCanvas) {alert("canvas undefined, does not seem to be supported by your browser");} if (!mainCanvas.getContext) {alert('Error: canvas.getContext() undefined !');} // Get the context for drawing in the canvas var mainContext = mainCanvas.getContext('2d'); if (!mainContext) {alert("could not get the context for the main canvas");} this.getMainCanvas = function () { return mainCanvas; } this.getMainContext = function () { return mainContext; } // Prepare a second canvas on top of the previous one, kind of second "layer" that we will use // in order to draw elastic objects like a line, a rectangle or an ellipse we adjust using the mouse // and that follows mouse movements var frontCanvas = document.createElement('canvas'); frontCanvas.id = 'canvasFront'; // Add the temporary canvas as a second child of the mainCanvas parent. mainCanvas.parentNode.appendChild(frontCanvas); if (!frontCanvas) { alert("frontCanvas null"); } if (!frontCanvas.getContext) { alert('Error: no frontCanvas.getContext!'); } var frontContext = frontCanvas.getContext('2d'); if (!frontContext) { alert("no TempContext null"); } this.getFrontCanvas = function () { return frontCanvas; } this.getFrontContext = function () { return frontContext; }
如果您有权访问创建画布的代码 - 只需在创建画布后立即调用该函数。
如果您无法访问该代码(例如,如果它是第三方代码,例如谷歌地图),那么您可以做的是测试是否存在间隔:
var checkExist = setInterval(function() { if ($('#the-canvas').length) { console.log("Exists!"); clearInterval(checkExist); } }, 100); // check every 100ms
但请注意 - 很多时候,第 3 方代码在完成加载时可以选择激活您的代码(通过回调或事件触发)。那可能是您可以放置函数的地方。区间解决方案确实是一个糟糕的解决方案,只有在没有其他方法的情况下才应该使用。