Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - Why CORS on Images with HTML Canvas?

Recently, I spent a bit of time researching a solution to a rather common problem in web development- I was dealing with logos middle-aligned on a transparent background, but having to place text below them, it would then appear as though the amount of whitespace between the text and the image shifts from page to page. After a bit of research, I discovered I could re-align the images bottom-left using a canvas, and the solution worked beautifully... at least until I integrated the solution into our code-base and discovered it was failing with:

"Unable to get image data from canvas because the canvas has been tainted by cross-origin data." (Say what!?)

Looking into it, the offending code was located at the first line of the following function:

getColumn: function (context, x, y, imageHeight) {
    var arr = context.getImageData(x, y, 1, imageHeight).data; //<-- CORS HATES THIS!
    return pvt.normalizeRGBArray(arr)
}

Now, I understand perfectly well what the CORS standard is, and I know the solution to this problem. The server needs to support CORS first. Either the server can set the http header access-control-allow-origin: "*", or allow a developer to set the crossDomain attribute for the image to "anonymous"/"use-credentials". This is all fine and dandy except when you work on the front-end for a big company where convincing the server-lords to change anything related to security is a non-starter conversation.

So really, my question here is what IS the logic behind having this security error occur with images on a canvas? They are frickin' images for crying out loud! It is fine to download them, hot-link to them, use them in memory, but "oh no!" don't manipulate them in any way whatsoever, or CORS throws an error!

If you ask me, the image is not tainted, it's this hairbrained CORS standard that is. Can somebody please explain the logic for why this happens? How could using a canvas to manipulate an image possibly be a security concern?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

Source: MDN


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...