gpt4 book ai didi

javascript - 让函数等到元素存在

转载 作者:IT王子 更新时间:2023-10-29 02:39:40 25 4
gpt4 key购买 nike

我正在尝试在另一个 Canvas 上添加一个 Canvas – 如何让此功能等到第一个 Canvas 创建后再开始?

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

最佳答案

如果您有权访问创建 Canvas 的代码 - 只需在创建 Canvas 后立即调用函数即可。

如果您无权访问该代码(例如,如果它是第 3 方代码,例如谷歌地图),那么您可以做的是在一个区间内测试是否存在:

var checkExist = setInterval(function() {
if ($('#the-canvas').length) {
console.log("Exists!");
clearInterval(checkExist);
}
}, 100); // check every 100ms

但请注意 - 很多时候,第 3 方代码可以选择在完成加载时激活您的代码(通过回调或事件触发)。那可能是您可以放置​​函数的地方。区间解决方案确实是一个糟糕的解决方案,只有在其他方法都不起作用时才应使用。

关于javascript - 让函数等到元素存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16149431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com