How to save canvas which include image? - javascript

I am trying to save my canvas which include image. I was trying use toDataURL, but it doesn't work on this case. The canvas is work to input the image inside.
HTML
<img src="bg.png" id="toIMG" />
<canvas></canvas>
<img alt="UNCHANGED" id="getCtx">
<span>Why does the img doesn't change?</span>
JS
window.onload = function(){
var c, ctx, img, img2;
c = document.querySelector("canvas");
ctx = c.getContext("2d");
img = document.getElementById("toIMG");
ctx.drawImage(img, 0,0, c.width, c.height);
img2 = document.getElementById("getCtx");
img2.src = ctx.canvas.toDataURL("image/png");
}

Instead of running the function when window has loaded, run it when the img has loaded. Also, as #CrissCrossCrass has pointed out, toDataURL is a method of canvas but not context.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<img
id="toIMG"
src="https://source.unsplash.com/random/120x120"
crossorigin="anonymous"
/>
<canvas></canvas>
<img id="getCtx" />
<script>
var c = document.querySelector("canvas");
var img = document.getElementById("toIMG");
var img2 = document.getElementById("getCtx");
var ctx = c.getContext("2d");
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0, c.width, c.height);
img2.src = c.toDataURL("image/png");
};
</script>
</body>
</html>
Also, you may want to set the crossOrigin attribute of the first img element to be anonymous to avoid tainted canvas. Read more about it

I tried that and actually it's working. Share if the console drops any error. Then i'll update my answer depending on it.

Related

How to copy PIXI's view into another canvas

In theory it should be as easy as :
//targetCanvas is a canvas node
//app is instance of PIXI.Application
targetCanvas.drawImage(app.view, 0, 0);
But, trust me, It doesn't work!
Sometime (yes, I said sometime) it does work if I add some delay before copying the image into the targetCanvas. ... So, I wonder if there is an asynchronous process happening when PIXI is rendering... but I can not find this information in PIXI's documentation.
var loadImage = async function(imgPath) {
return new Promise((resolve, reject) => {
var img = document.createElement("img");
img.onload = ()=> {
resolve(img);
}
img.src = imgPath;
})
}
var canvasTag = document.querySelector("#canvasVideo");
var canvasCtx = canvasTag.getContext("2d");
var canvasResult = document.querySelector("#canvasResult");
var canvasResultCtx = canvasResult.getContext("2d");
var canvasWidth = canvasTag.width;
var canvasHeight = canvasTag.height;
var canvasWidth = 320;
var canvasHeight = 240;
const app = new PIXI.Application({
view: document.querySelector("#glCanvas"),
transparent: true,
width: canvasWidth,
height: canvasHeight
});
const container = new PIXI.Container();
const renderer = PIXI.autoDetectRenderer();
app.stage.addChild(container);
(async ()=> {
var imgTag = await loadImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAA5FBMVEX71DP///8AAAAUFRgAABb/2DT/2jT/3DX70yn70h3/3TX70RX70iT70y0AABURExj710T96J/+8cb84oT20DL//ff844n/+ur+9NL++OMLDxj85I784Hj72lr+997//vr966383mz96aPXti6ZgibvyjH97ru6nioACRfDpSj+8sn+9NT72VAdHBlDOxzqxjFwYCEsKBpNQx07MgxfURNzYReMeCR9ayJfUh/83nEnIQiskSOBbRoRDgONdxzUsystJgk9NhwhHxmwlikvKhpzYiFHPA4dGAa+oCZSRhA0LAtCOA1YRGDzAAANp0lEQVR4nO2dWVvbuhaGlcFTbIUMzkASAxkhDE1LobsQIC3sckrP//8/R3EmD5IsWXKw6fkuekEfxXq9pLWWZA0gl7garXZtUu3W+06lYgMA7ErF6fea3cGk3Wok/3iQ5I+32oOmU7FMw7AsXYcQbAQh1HXLMkwDOPXB+WGSlUiKsFWr9qFpWF4urKCOQE2nW2slVJMkCFuTZgWZLQItwGkYdm+SBKV0wovupWnoPHQea5qVblt2heQS1no6n+0wttR7Nan+RyLheR1VT4BuI9Rge+fyqiWL8LArB28DqXePJNVMDmHNMeXhrSHNy4mUukkgbFV1Q6TvkQQNqyrBuQoTHtYNKwG8lSyjLswoSHjUl948/dLNnmDGI0R42DeTaJ5BxjshOwoQtnoJ22/HWBeIkLEJj7t74nMZjerxvgknMDn/gpMF48aOeISHl8Ze+ZYynHguJxZhdw8OJixodvdE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3lMi7Z0ZBIyJ2yNupDPMB77iQSCjxriA0fFiMaEOHdeN8WijSJiL9kQJLKPe+JzR0txej2x8kupun6ViVOM8avIIFSyj9XjlkypIynM5HDzdvr1/vH/OPf17fbh5GL2jYKJMOCUIMTvhPidwN6A550ZjXJVK01YBY+lMY7137+HfnZff+QxsLg/vjRTbXfpsXzIQZvYe0imX5W++SzeB9wBDy3Qecvetkee90zuUG2UI08ZcB0whzvSxFRatH5CATZuk2S5KXiSBswKwgQnBMxqAQ5g4zEhWh0aJQ0Aizktvg7+NmIszVsoBIjBMshLlJ+hHNGh0hgjB3knZE8ySCIIow7YiRgNGE6UaMBmQgTDMiAyALYXrdjRmc/Y1LmNKgAc1zlsozEaKxVPoSOGhRAz0nYe4Ipm1IrANaqsZPmGtcpmswZTmUZDsWIRovpikPN+vRFeYmzFVT0xkhS5SIQZhrp6Qz6jo9145PmGs4aWiphkOYVZNAmIaWCslzTlIIc0eV9/WpFsBO3UskzOW672hGaOK+LskmzLXBe5nRsnkNGI/wvcwIzfAn7KQIc4f7d6rQdEKLEBIkRCMquN+maoGI6RjphLnjqrG/+K8Tvg0mSojif93cD6NuNrlivDTCXK51twdG3ewxjpMSIEQup5cwI+KL52BkESI71o3kfI5l1YXsJ4UQMVYtI4n4CA2rKtD/JBIiTRzpjVU3nbjxwS85hKhDdnWJ0QP9Vlew+20lixDpvGdIgdQNq8czxI2QREIUIWs99PZF+iRE5Xs11kkmJkklXKrdrJhWLEpEZ1a6MUYPdEknRGpN6rZhWDyU0DKMSnMiHBowSoJwqVat2jdMI9KaEOqWYer9ai0JuqWSInTVap80HYBAEakOPUs7EJduIbOZVsVpDs6TgnOVKOFKjVa7dtKt9/pOZSOnX+8OJucXLQkRPUr/A5yNC0f3lG+mAAAAAElFTkSuQmCC");
canvasCtx.drawImage(imgTag, 0, 0, canvasWidth, canvasHeight);
var bgSprite = PIXI.Sprite.from(imgTag);
app.stage.addChild(bgSprite);
canvasResultCtx.drawImage(document.querySelector("#glCanvas"), 0, 0);
})()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://pixijs.download/release/pixi.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="canvasVideo" width="320" height="240" autoplay></canvas>
<canvas id="glCanvas" width="320" height="240" autoplay></canvas>
<canvas id="canvasResult" width="320" height="240" autoplay></canvas>
</body>
</html>
canvasVideo (left) is normal canvas with 2d context.
glCanvas (middle) is a PIXI's view
canvasResult (right) is a normal canvas where a PIXI view should be copied into.
We don't have any problem copying canvas into PIXI. (except the CORS prevents the webGL renders the image correctly)
But, as you can see, the third canvas is blank. I wonder if there is any solution to this issue... without using PIXI's ticker or setTimeout?
You don't need to use the PIXI ticker or a custom timer (requestAnimationFrame as in your own response) to render to the canvas. There's the possibility to simply call app.render() in a synchronous way after the desired elements are added to the stage.
On top of that, if you want to prevent having a running application that renders on each frame, you may want to add autoStart: false to your Application config.
var loadImage = async function(imgPath) {
return new Promise((resolve, reject) => {
var img = document.createElement("img");
img.onload = ()=> {
resolve(img);
}
img.src = imgPath;
})
}
var canvasWidth = 320;
var canvasHeight = 240;
const app = new PIXI.Application({
view: document.querySelector("#glCanvas"),
transparent: true,
width: canvasWidth,
height: canvasHeight,
autoStart: false,
});
(async () => {
var imgTag = await loadImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAA5FBMVEX71DP///8AAAAUFRgAABb/2DT/2jT/3DX70yn70h3/3TX70RX70iT70y0AABURExj710T96J/+8cb84oT20DL//ff844n/+ur+9NL++OMLDxj85I784Hj72lr+997//vr966383mz96aPXti6ZgibvyjH97ru6nioACRfDpSj+8sn+9NT72VAdHBlDOxzqxjFwYCEsKBpNQx07MgxfURNzYReMeCR9ayJfUh/83nEnIQiskSOBb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GI/wvcwIzfAn7KQIc4f7d6rQdEKLEBIkRCMquN+maoGI6RjphLnjqrG/+K8Tvg0mSojif93cD6NuNrlivDTCXK51twdG3ewxjpMSIEQup5cwI+KL52BkESI71o3kfI5l1YXsJ4UQMVYtI4n4CA2rKtD/JBIiTRzpjVU3nbjxwS85hKhDdnWJ0QP9Vlew+20lixDpvGdIgdQNq8czxI2QREIUIWs99PZF+iRE5Xs11kkmJkklXKrdrJhWLEpEZ1a6MUYPdEknRGpN6rZhWDyU0DKMSnMiHBowSoJwqVat2jdMI9KaEOqWYer9ai0JuqWSInTVap80HYBAEakOPUs7EJduIbOZVsVpDs6TgnOVKOFKjVa7dtKt9/pOZSOnX+8OJucXLQkRPUr/A5yNC0f3lG+mAAAAAElFTkSuQmCC");
var bgSprite = PIXI.Sprite.from(imgTag);
app.stage.addChild(bgSprite);
app.render();
})()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://pixijs.download/release/pixi.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="glCanvas" width="320" height="240"></canvas>
</body>
</html>
The ticker is not used for non-animated sprites, but apparently pixi still needs ONE frame to draw everything before you can copy it.
I was able to solve your issue with one requestAnimationFrame
(async ()=> {
var imgTag = await loadImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAA5FBMVEX71DP///8AAAAUFRgAABb/2DT/2jT/3DX70yn70h3/3TX70RX70iT70y0AABURExj710T96J/+8cb84oT20DL//ff844n/+ur+9NL++OMLDxj85I784Hj72lr+997//vr966383mz96aPXti6ZgibvyjH97ru6nioACRfDpSj+8sn+9NT72VAdHBlDOxzqxjFwYCEsKBpNQx07MgxfURNzYReMeCR9ayJfUh/83nEnIQiskSOBbRoRDgONdxzUsystJgk9NhwhHxmwlikvKhpzYiFHPA4dGAa+oCZSRhA0LAtCOA1YRG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mSojif93cD6NuNrlivDTCXK51twdG3ewxjpMSIEQup5cwI+KL52BkESI71o3kfI5l1YXsJ4UQMVYtI4n4CA2rKtD/JBIiTRzpjVU3nbjxwS85hKhDdnWJ0QP9Vlew+20lixDpvGdIgdQNq8czxI2QREIUIWs99PZF+iRE5Xs11kkmJkklXKrdrJhWLEpEZ1a6MUYPdEknRGpN6rZhWDyU0DKMSnMiHBowSoJwqVat2jdMI9KaEOqWYer9ai0JuqWSInTVap80HYBAEakOPUs7EJduIbOZVsVpDs6TgnOVKOFKjVa7dtKt9/pOZSOnX+8OJucXLQkRPUr/A5yNC0f3lG+mAAAAAElFTkSuQmCC");
canvasCtx.drawImage(imgTag, 0, 0, canvasWidth, canvasHeight);
var bgSprite = PIXI.Sprite.from(imgTag);
app.stage.addChild(bgSprite);
requestAnimationFrame(() => {
canvasResultCtx.drawImage(document.querySelector("#glCanvas"), 0, 0);
});
})()

Cannot read property 'getContext' of null (no jQuery)

I'm trying to make a game with canvas but I have a problem. my problem is with the const ctx = canvas.getContext("2d");
I have the error Cannot read property 'getContext' of null
I looked at the other posts nothing helped my problem
(I don't use jquery)
thank you in advance for your future answers <3
Here is my HTML code and JS CODE :
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Human Run</title>
<link href="./style.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Human Run</h1>
<div class="score-container">
<div id="bestScore"></div>
<div class="currentScore"></div>
</div>
</header>
<canvas class="landscape" id="fond" width="350" height="416"></canvas>
<canvas class="ground" id="sol" width="350" height="150"></canvas>
<script src="./script.js" type="text/javascript" ></script>
<script src="./ground.js" type="text/javascript" ></script>
</body>
</html>
JS CODE :
const canvas = document.getElementById('sol');
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = '.media/ground2.png';
// réglages général
const speed = 6.2;
const render = () => {
index++;
// background
ctx.drawImage(img, 0, 0, canvas.width, canvas.height, -((index * (speed / 2)) % canvas.width) + canvas.width, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height, -((index * (speed / 2)) % canvas.width), 0, canvas.width, canvas.height);
window.requestAnimationFrame(render);
}
img.onload = render;
Your problem seems to be simply that your javascript loads before your html, as a result, your javascript tries to use an element("sol") that does not exist at the time because it is not there yet. Two solutions either put async on your javascript <script> tag
https://www.w3schools.com/tags/att_script_async.asp
or surround your code with document.addEventListener("DOMContentLoaded",()=>{/* your code goes here*/});
https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event
document.addEventListener("DOMContentLoaded",()=>{
const ctx = sol.getContext("2d");
const img = new Image();
let index = 0;
img.src = 'http://fc04.deviantart.net/fs70/i/2012/014/c/9/rpg_floor_tiles_02_by_neyjour-d4me7dx.jpg';
// réglages général
const speed = 6.2;
const render = () => {
index++;
// background
ctx.drawImage(img, 0, 0, sol.width, sol.height, -((index * (speed / 2)) % sol.width) + sol.width, 0, sol.width, sol.height);
ctx.drawImage(img, 0, 0, sol.width, sol.height, -((index * (speed / 2)) % sol.width), 0, sol.width, sol.height);
window.requestAnimationFrame(render);
}
img.onload = render;
});
<header>
<h1>Human Run</h1>
<div class="score-container">
<div id="bestScore"></div>
<div class="currentScore"></div>
</div>
</header>
<canvas class="landscape" id="fond" width="350" height="416"></canvas>
<canvas class="ground" id="sol" width="350" height="150"></canvas>

Why I cannot preview image uploaded by inputfield and show it in canvas?

I need to upload an image and show it in canvas in browser. First time when I upload this image, canvas width and height are zero, but second time the image is appearing correctly? Why?
function previewFile() {
const canvas = document.getElementById('canvas');
const img = document.createElement('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
img.src = reader.result;
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="./script.js"></script>
<title>Document</title>
</head>
<body>
<input type="file" onchange="previewFile()"><br>
<canvas id="canvas"></canvas>
</body>
</html>
When you setting the image src, it doesn't loaded synchonous, so you have to wait for image load event, and only then draw it on the canvas.
A lot of operations in JS connected with resources are of asynchronous nature, so you have to deal with it.
function previewFile() {
const canvas = document.getElementById('canvas');
const img = document.createElement('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
img.src = reader.result;
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
}
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="./script.js"></script>
<title>Document</title>
</head>
<body>
<input type="file" onchange="previewFile()"><br>
<canvas id="canvas"></canvas>
</body>
</html>

Transparent background turns black after converting into webp format via HTML5 canvas

I got a problem with converting PNG image to webp format. The background turns black instead of remaining transparent.
How can I fix this?
var img = document.querySelector('#sample');
var webp = document.querySelector('#webp');
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight);
webp.src = canvas.toDataURL('image/webp');
};
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAABAJSURBVHja7FtbbB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jjG11H6928q+iDiStKozf1T1PX6dCqK/Cv86ybtsW3+t/n/yvAAHNTLm1nQ+TCAAAAAElFTkSuQmCC';
<img id="sample">
<img id="webp">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image()
img.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAABAJSURBVHja7FtbbBxXGZ6Z9dq7tmPHceLYSZy0DUnTpiFtgqKKKkWgAkIqpXloEVAekKiEBEVFiMsTTwjxghBIfeAVqQgJBH0A8YbShkqoLSlqAZFQaHCuxM3NsXdt784cvu/s/4//PZl1dpuSVgoj/Tozs3M53/dfz5mzsXMuupW3JLrFt/8TcKsT0Fd08tVXX131plKp1GIvSfw+2ziOc9Hf7TlcM4JTU9jfgnYS7XrIIIQXp2jn0b6F9hTkJPbPQpb0ORqr2IaSpmmUZZlvm81m1Cmu3Xnnnd0R8A5tMWQa8n50aDc6twUkjBE02n6QVEbL95diIvTYPKAU+zXIechxyCuQP0Eu3zQLuMGtHyD2o30Q7U60w319feX+/v6Bcrk8iP0qCYCURfuJati1VNeENpsgbBKyB6c+hXPnIC9CfgM59l4lgPHkADr/MDp+B90CgJNqtToyMDCwDsBp7n2i7ViAJy0L91u+L8/Do7IGTHoBMo1nfhZkfBLnn4f8FPLP9xIB7OBn0MG96H8G824MDg6ug0xA88NCjgeIayzgRMhQKYnP+2M8ZwBCC1psNBpzkCrufwTEHMTvP8P+s2jr7xoB7Cc68xDkcZo6O4POVkZGRjYD/AaaOYMTwQqoJF7ZEktMQpORfSXAtdiK8MxhEFGFXF1eXmYsGMJzv4z2flzyfbRvvBsE9EPrT6ADD2F/GR2tQ9vV0dHRLTB7RviE/TdaDjWu/t9GjmljQzRjQwnPHyOpi4uLl/DsOvbvxflnQMb3xDVuWh0wCPBfgUl+FP5ZQwdSdGYA4DdX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1DwH8gZ+SvN1d7JUA10icaJwlcYLBWjtUFyoaIJFgab8nI1JoxZhiCdrnuqCKrwROZT1iGdgl8AYbCFehLAq5kFnNlwfRcKsCtG9QE8EXR/mWNB28nCCYCjpYwKNqvBjGgPyCiFCyVSYLVaKutDbTk2etSQ6Q1edW6Bj2NAXUhoibENG80DZbMOn+VctD2BdZQREISpNWoIBC6Ai2HJDQNeLtvj+3171ghFAc+H5p8KVgBnhQcR9ebEisgIiTFEuOCvN/Rwoqw9vp/AfvgNAATd1jjG11H6928q+iDiStKozf1T1PX6dCqK/Cv86ybtsW3+t/n/yvAAHNTLm1nQ+TCAAAAAElFTkSuQmCC";
setTimeout(function(){cxt.drawImage(img,0,0);},2000);
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="100"></canvas>
</body>
</html>
this is my test with your picture,so I think there is no problem in your code.

How to get the color of a pixel from image?

I want to get the color of a pixel from image with using pure JavaScript.
I wrote this script, but it did not work:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Get Pixel</title>
<script type='text/javascript'>
window.onload = function() {
var canvas = document.createElement("canvas");
var pic = new Image();
pic.src = 'http://i.imgur.com/hvGAPwJ.png';
pic.onload = function() {
canvas.width = pic.width;
canvas.height = pic.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(pic, 0, 0);}
var c = canvas.getContext('2d');
var p = c.getImageData(7, 7, 1, 1).data;
var hex = "RGB = " + p[0]+", "+p[1]+", "+p[2];
document.getElementById("output").innerHTML = hex;
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
How to change the code, what would he worked correctly?
For example for the picture "http://i.imgur.com/hvGAPwJ.png", the result should be RGB = 255, 255, 255.
Your code is almost (see below) correct in its self BUT unfortunately when you use images from other origins than the page itself certain criteria must be there for it to work due to CORS (security feature).
You cannot use images from other origins out of the box. The server they are on need to have accept-* header set to allow this.
If not your getImageData and toDataURL will be blank (throws a security error that you can see in the console).
If you don't have access to modify the server the only way to get around this is to use your own server as a image proxy (http://myServer/getImage.cgi|php|aspx...?http/otherServer/img)
As pointed on in comments always set src after onload so you are sure onload gets initialized.
var pic = new Image();
pic.onload = function() { /* funky stuff here */ };
pic.src = 'http://i.imgur.com/hvGAPwJ.png'; //Last
If you indent your script properly, the error becomes more apparent:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Get Pixel</title>
<script type='text/javascript'>
window.onload = function() {
var canvas = document.createElement("canvas");
var pic = new Image();
pic.src = 'http://i.imgur.com/hvGAPwJ.png';
pic.onload = function() {
canvas.width = pic.width;
canvas.height = pic.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(pic, 0, 0);
}
var c = canvas.getContext('2d');
var p = c.getImageData(7, 7, 1, 1).data;
var hex = "RGB = " + p[0]+", "+p[1]+", "+p[2];
document.getElementById("output").innerHTML = hex;
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
You are setting a function on the image's load event, but not waiting for it to happen before you update the contents of the div.
You should move everything inside the pic.onload function, apart from setting the pic.src:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Get Pixel</title>
<script type='text/javascript'>
window.onload = function() {
var canvas = document.createElement("canvas");
var pic = new Image();
pic.onload = function() {
canvas.width = pic.width;
canvas.height = pic.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(pic, 0, 0);
var c = canvas.getContext('2d');
var p = c.getImageData(7, 7, 1, 1).data;
var hex = "RGB = " + p[0]+", "+p[1]+", "+p[2];
document.getElementById("output").innerHTML = hex;
}
pic.src = 'http://i.imgur.com/hvGAPwJ.png';
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Now the problem is just cross origin restrictions.
To solve cross origins restrictions, you may add this line:
pic.crossOrigin = "Anonymous";
Right after defining pic var.
May not work in some cases though.

Categories

Resources