Creating a CanvasImageData object without an instance of canvas in JS
I'm new to Javascript. I'm doing some image processing using canvas, and I'm trying to create a new CanvasImageData object without actually referencing a specific Canvas.
ie.
oImageData = CanvasRenderingContext2D.createImageData(vCSSWidth, vCSSHeight)
(from MSDN)
// Why can't I write:
var image_data = CanvasRenderingContext2D.createImageData(50, 50);
// or:
var image_data = CanvasRenderingContext2D.prototype.createImageData(50, 50);
// ?
// Instead I must do:
var canvas = do开发者_如何学JAVAcument.createElement("canvas");
var image_data = canvas.createImageData(50, 50);
Is there a way to do this without an instance of Canvas? If not is there a reason why?
Thanks!
You can certainly reference createImageData
off of the interface prototype object:
CanvasRenderingContext2D.prototype.createImageData.call({ }, 100, 100); // ImageData
However, some environments (WebKit, for example) add restrictions on the type of object in context of which createImageData
method (and likely others) is to be called:
CanvasRenderingContext2D.prototype.createImageData.call({ }, 100, 100); // TypeError: Illegal invocation
This works in at least Firefox nightly (just checked).
Reminds me of other WebKit's context restriction with console.log
:
console.log.call({ }, 1); // TypeError: Illegal invocation
console.log.call(console, 1); // logs 1
new ImageData(50, 50) works in Edge, Chrome, Opera, and Firefox now in 2023.
The ImageData constructor works in web workers but CanvasRenderingContext2D is not defined in workers.
精彩评论