Any-Kind-Soul-Out-there,
I spending hours figuring out how could i done the coding in such a way that when after user drawn on the canvas, they can click a btn called "save". After which the canvas's image will appear as a BG img of the webpage.
Even after user close the web browser, the bg img is still there when user open it again. I'm not sure is it possible to do it or not.
Need some help here, if need my full coding i can provide.
Below is my current coding when user clicked "save" btn. (Open new window as an image.)
// Save image
var saveImage = document.createElement("button");
saveImage.innerHTML = "Save canvas";
saveImage.addEventListener("click", function (evt) {
window.open(canvas.toDataURL("image/png"));
evt.preventDefault();
}, false);
document.getElementById("main-content").appendChild(saveImage);
You might use toDataURL to set the background, and localStorage to store 'permanently' the image :
http://jsbin.com/japekuzi/1/
use draw to fill the canvas with random rects, and set button to set and store current canvas as background.
Notice that when you (re)run the jsbin, it stills keeps its latest background.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<canvas id='cv'></canvas>
<button id='dr'>draw</button>
<button id='st'>set</button>
</body>
</html>
JS :
var $=document.getElementById.bind(document);
var cv = $('cv');
var ctx = cv.getContext('2d');
function randFill() {
ctx.clearRect(0,0,cv.width, cv.height);
for(var i=0; i<10; i++) {
var c= 0 | ( Math.random()* 360);
ctx.fillStyle = 'hsl('+c+',75%,75%)';
ctx.fillRect(Math.random()*cv.width*0.8,
Math.random()*cv.height*0.8, 20, 20);
}
}
function set() {
localStorage.setItem("bg", cv.toDataURL());
retrieve();
}
function retrieve() {
var cvURL = localStorage.getItem("bg", cv.toDataURL());
if (!cvURL) return;
document.body.style. backgroundImage ='url('+ cvURL+')';
}
randFill();
retrieve();
$('dr').onclick=randFill;
$('st').onclick=set;
Related
I have JavaScript code in my site.
The code is using 2 identical photos-same size, same resolution - only different colors.
First photo is black and white photo - this is what the canvas presents.
Second photo is the same only with the original colors.
I have a button that triggers JS code - which generally removes a pixel from the black and white -and paints color pixel on the canvas. At first I used Math.random for the pixel locations.
And than I decided to use it by order. No matter where it starts or begging.. as long it will go
in this order (x,y)..(x+1,y).. until maximum x.. and than (x,y+1).. until maximum x.. and so on until all the black and white photo "transformed" into the colorful photo..
for some reason I just cant make it happen.. i tried a lot of techniques..
here is demo for global understanding:
demo is working sorry - they deactivated my free host :\ hope you still understand..
here is the original code- i just changed the last function : **removeDrawRandomPixel** ..it's just playing the function there and it should be fixed..
///////////////////////global variables///////////////////
var gray_url="bwcat.jpg"; //black and white image URI
var regular_url="cat.jpg"; //regular image URI
var n=100; //number of pixels changed per click
/////////////////////////////////////
document.addEventListener("DOMContentLoaded", function(){
var c=new EditableCanvas(document.getElementById('cnvs'));
grayScaleImage=new Image();
grayScaleImage.src=gray_url;
grayScaleImage.onload=function()
{
c.drawImage(this);
}
regularImage=new Image();
regularImage.src=regular_url;
regularImage.onload=function()
{
var p=getPixelArray(this);
btn.onclick=function(){
for(var i=1;i<=n&&p.length>0;i++){
removeDrawRandomPixel(p,c);
}
}
}
},false);
//create a Pixel object
function ImagePixel(x,y,r,g,b,a)
{
this.x=x;
this.y=y;
this.r=r;
this.g=g;
this.b=b;
this.a=a;
}
//object that allows custom methods
function EditableCanvas(canvas)
{
this.canvas=canvas;
this.context=canvas.getContext('2d');
this.width=canvas.width;
this.height=canvas.height;
this.pixelImage=this.context.createImageData(1,1);
//draw an entire picture and adjust the canvas for it
this.drawImage=function(image)
{
this.width=image.width;
this.height=image.height;
this.canvas.height=image.height;
this.canvas.width=image.width;
this.context.drawImage(image,0,0);
}
//draw a single pixel, ImagePixel pixel
this.drawPixel=function(pixel)
{
this.pixelImage.data[0]=pixel.r;
this.pixelImage.data[1]=pixel.g;
this.pixelImage.data[2]=pixel.b;
this.pixelImage.data[3]=pixel.a;
this.context.putImageData(this.pixelImage,pixel.x,pixel.y);//,pixel.x,pixel.y);
}
}
//the function returns an ordered array of Pixel pixels of the image at `src`.
function getPixelArray(img)
{
var pixelArray=[];
var cnvs=document.createElement('canvas');
cnvs.width=img.width;
cnvs.height=img.width;
var context=cnvs.getContext('2d');
context.drawImage(img,0,0);
var originalData = context.getImageData(0,0,img.width,img.height).data;
for(var i=0,pixelId=0,px;i<originalData.length;i+=4)
{
px=new ImagePixel(pixelId%img.width,Math.floor(pixelId/img.width),originalData[i],originalData[i+1],originalData[i+2],originalData[i+3]);
pixelArray.push(px);
pixelId++;
}
return pixelArray;
}
//the function remove a random pixel from pixelArray and draws it on editableCnvs
function removeDrawRandomPixel(pixelArray,editableCnvs)
{
var place=Math.floor(Math.random()*pixelArray.length);
var px=pixelArray.splice(place,1)[0];
editableCnvs.drawPixel(px);
}
html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas rules</title>
<script src="pixel.js"></script>
</head>
<body>
<canvas id="cnvs">
oh goddmamit no support
</canvas>
<button id="btn">click to convert</button>
</body>
</html>
I tried playing the last function.. because i know the answer is in the function,how to choose the pixels..
This is untested however this is what I would change the removeDrawRandomPixel function to. You are grabbing a random point in the array currently and passing it, so it could be starting on the blue component of one pixel and ending on the g component of another pixel.
//the function remove a random pixel from pixelArray and draws it on editableCnvs
function removeDrawRandomPixel(pixelArray,editableCnvs)
{
// width and height need to be the width and height of the canvas.
var width = canvas.width,
height = canvas.height,
x = Math.floor(Math.random()*width),
y = Math.floo(Math.random()*height);
var px = (y * width + x) * 4;
editableCnvs.drawPixel(px);
}
I'm creating a HTML5 game which can be made to run on Android also. I went through few articles and didn't get the solution yet. I have a image which i'm generating through javascript and I want to move this image using touchmove so that I can run it in my Android device. This is the code:
gameCanvas.addEventListener("touchmove", touchXY, true);
function touchXY(e) {
if (!e)
var e = event;
e.preventDefault();
avatarX = e.targetTouches[0].pageX - gameCanvas.offsetLeft;
avatarY = e.targetTouches[0].pageY - gameCanvas.offsetTop;
}
This is not working. I got this code from https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HTML-canvas-guide/AddingMouseandTouchControlstoCanvas/AddingMouseandTouchControlstoCanvas.html
And this is my canvas:
<canvas id="gameCanvas" onclick="setUpGame();" width="400" height="300"></canvas>
This is my image:
avatarImage.src = "img/avatar.png";
gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
I just want to move the image inside the canvas.
I wrote a full example, hopefully it's not too verbose.
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
</head>
<body>
<canvas id='canvas' width='512' height='512'></canvas>
<script>
var c=document.getElementById('canvas'),
ctx=c.getContext('2d'),
activeBox='none',
//populate the map with objects
box=[
{
x:256,
y:128,
width:32,
height:64
},
{
x:128,
y:64,
width:64,
height:64
},
{
x:32,
y:32,
width:32,
height:32
},
];
function draw(){
//clear the screen, draw population
ctx.clearRect(0,0,c.width,c.height);
for(var i=0;i<box.length;i++){
ctx.fillRect(box[i].x,box[i].y,box[i].width,box[i].height);
}
//repeat at 60fps if possible, pause if window looses focus
requestAnimationFrame(draw);
}
function startTouch(e){
//this makes it easier to write control flow later and keeps XY relative to canvas
var xTouch=e.touches[0].pageX-c.offsetLeft,
yTouch=e.touches[0].pageY-c.offsetTop;
//its best to go through this loop in touchstart, because it only happens once per touch
for(var i=0;i<box.length;i++){
if(xTouch>box[i].x&&xTouch<box[i].x+box[i].width){
if(yTouch>box[i].y&&yTouch<box[i].y+box[i].height){
activeBox=i;
}
}
}
}
function moveTouch(e){
//grab a box by the center
if(activeBox!='none'){
box[activeBox].x=e.changedTouches[0].pageX-box[activeBox].width/2;
box[activeBox].y=e.changedTouches[0].pageY-box[activeBox].height/2;
}
}
function endTouch(){
//clear active so that dragging empty space wont move the last active box
activeBox='none';
}
canvas.addEventListener('touchstart',startTouch);
canvas.addEventListener('touchmove',moveTouch);
canvas.addEventListener('touchend',endTouch);
window.addEventListener('load',draw);
</script>
</body>
</html>
I used fillRect for simplicity, but if you want to replace it with drawImage you'll need to create a new element for each and add a source property to the box object array. Here's a partial example.
//you need a new one of these for every image
var img=new Image();
img.src='http://www.w3schools.com/images/w3logotest2.png';
var box={
source:img,
x:Math.floor((Math.random()*256)+1),
y:Math.floor((Math.random()*256)+1)
};
//make sure the image doesnt load before the script
window.onload=function(){
ctx.drawImage(img,box.x,box.y);
}
I'm trying to use the element to draw a static Google Maps image that comes onscreen once a user clicks on a submit button. The html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=true">
</script>
<script type="text/javascript" src="createmap.js">
</script>
</head>
<body>
<form onsubmit="display_map(34.1,-76.08168); return false;">
<input type="submit" value="Submit"/>
</form>
<canvas id='map-canvas' />
</body>
</html>
And the display_map() function in createmap.js:
function display_map(center0, center1) {
var image = new Image();
image.src = 'http://maps.googleapis.com/maps/api/staticmap?center='
+ center0 + ',' + center1 + '&zoom=13&size=800x800&sensor=false';
var canvas = document.getElementById('map-canvas');
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
}
The first time that the user clicks on the submit button, nothing happens. Every subsequent click, however, will load the image (even if the tab is closed and then reopened). Changing the center0 and center1 arguments will reset the page and again force two clicks to display the new image that Google generates. This behavior doesn't seem to be coming from Google Maps, as the same issue occurs when I load an image from my hard drive. This is happening in every browser I've tested (Firefox, IE and Chrome).
It's because the first time the image hasn't loaded properly so the canvas doesn't draw anything. The image loads asynchronous in the background so your function will continue regardless.
To handle this scenario try with:
function display_map(center0, center1) {
var image = new Image();
image.onload = function() {
var canvas = document.getElementById('map-canvas');
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0);
}
image.src = 'http://maps.googleapis.com/maps/api/staticmap?center='
+ center0 + ',' + center1 + '&zoom=13&size=800x800&sensor=false';
}
That the function returns immediately is something that needs to be taken into account in case you do several draw operations to canvas (graphics on top for instance).
For these cases you need to use callbacks so when an image has finished loading you call the next step from within the onload handler with a single extra parameter:
function display_map(center0, center1, callback) {
var image = new Image();
image.onload = function() {
var canvas = document.getElementById('map-canvas');
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0);
callback();
}
image.src = 'http://maps.googleapis.com/maps/api/staticmap?center='
+ center0 + ',' + center1 + '&zoom=13&size=800x800&sensor=false';
}
Now you can create a call chain:
function step1() {
display_map(center0, center1, step2);
}
function step2() {
/// called when step1 has finished
}
<html>
<head>
<meta charset="utf-8">
<title>Game</title>
<script src="http://code.createjs.com/easeljs-0.4.2.min.js"></script>
</head>
<body>
<div id ="beeld">
<canvas id ="stageCanvas" width="1024" height="576">
<script src ="javascript.js"></script>
</canvas>
</div>
</body>
</html>
This is my Html
//Javascript Document
var canvas = document.getElementById('stageCanvas');
var stage = new Stage(canvas);
var Background;
var imgBackground = new Image();
imgBackground.src ="images/bg.png";
Background = new Bitmap(imgBackground);
Background.x = 0
Background.y = 0
stage.addChild(Background);
stage.update();
And that's my js.
The image is 1024 by 576, so it should be fullscreen. The original is 2048 by 576. I was planning to do like the background would slide to left and repeat it self when it gets to the end.
So my question is, why doesnt the image show up on the canvas.
I'm a very new to this, so I'm sorry if I'm asking such an easy question.
PS: If I inspect the HTML, it DOESN'T show any errors and it DOES show that the image is being loaded. It's just not.. drawn.. I guess.
I'm getting frustrated, because I'm stuck here for a couple hours already.
I FOUND A WORKING CODE
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Easel simple game</title>
<script src="http://code.createjs.com/easeljs-0.4.2.min.js"></script>
<script>
var canvas;
var stage;
var bg;
var score;
var ghost;
function init() {
canvas = document.getElementById("StageCanvas");
stage = new Stage(canvas);
score = 0;
bg = new Image();
bg.src = "img/bg.png";
bg.onload = setBG;
}
function setBG(event){
var bgrnd = new Bitmap(bg);
stage.addChild(bgrnd);
stage.update();
}
</script>
</head>
<body onload="init();">
<canvas id="StageCanvas" width="1240" height="576"></canvas>
</body>
</html>
By the way this code is the work for someone else, so I don't take any credit.
This seems to work perfectly. But once I remove the
bg = new Image();
bg.src = "img/bg.png";
bg.onload = setBG;
it stops working.
Background = new Bitmap(imgBackground);
In HTML:
Try to move the script-tag of your javascript.js to right before the </body> or at least not into the <canvas>...</canvas>.
And another thing is: You have a space between src and = and id and =, that might cause problems in some browsers.
In JavaScript:
You need to execute the update-method with () otherwise that line will just be a listed reference to the update function.
stage.update();
And a second thing, that I noticed(though not part of the issue): You are using EaselJS 0.4.2, but 0.5.0 is already released, just in case you want to be up-to-date: http://code.createjs.com/easeljs-0.5.0.min.js ;-)
I'm having the same issue with EaselJS at the moment. While it might work for you, you can try and add a ticker which will automatically update the canvas:
createjs.Ticker.addListener(stage);
I was able to get the image to paint on the canvas after adding this, but as soon as I add any transforms to the image (scale, positioning, height, width) they are not applied prior to the image being drawn.
I've been scratching my head over this too.
Hey, I'm looking for a way to take a black and white img element, and using JavaScript, specify an RGB value so that the image becomes that color. Any ideas (aside from libraries)?
Also I'm trying to do this with IE only. The reason I'm doing it in IE only is because I'm making a small sidebar gadget.
In Internet Explorer, you could use Visual Filters.
Edit: you want to use the Light filter, here is an exemple
<STYLE>
.aFilter {
filter:light();
}
</STYLE>
<SCRIPT>
window.onload=fnInit;
function fnInit(){
oDiv.filters[0].addAmbient(50,20,180,100);
}
</SCRIPT>
with filter: <img CLASS="aFilter" ID="oDiv" src="http://cache2.artprintimages.com/p/LRG/8/853/2USY000Z/black-and-white-cats.jpg">
without: <img src="http://cache2.artprintimages.com/p/LRG/8/853/2USY000Z/black-and-white-cats.jpg">
Something like this?
Edit: Ah, no canvas. No worries.
<html>
<head>
<script type="text/javascript">
function createCanvas(image){
// create a new canvas element
var myCanvas = document.createElement("canvas");
var myCanvasContext = myCanvas.getContext("2d");
var imgWidth=image.width;
var imgHeight=image.height;
// set the width and height to the same as the image
myCanvas.width= imgWidth;
myCanvas.height = imgHeight;
// draw the image
myCanvasContext.drawImage(image,0,0);
// get all the image data into an array
var imageData = myCanvasContext.getImageData(0,0, imgWidth, imgHeight);
// go through it all...
for (j=0; j<imageData.width; j++)
{
for (i=0; i<imageData.height; i++)
{
// index: red, green, blue, alpha, red, green, blue, alpha..etc.
var index=(i*4)*imageData.width+(j*4);
var red=imageData.data[index];
var alpha=imageData.data[index+3];
// set the red to the same
imageData.data[index]=red;
// set the rest to black
imageData.data[index+1]=0;
imageData.data[index+2]=0;
imageData.data[index+3]=alpha;
delete c;
}
}
// put the image data back into the canvas
myCanvasContext.putImageData(imageData,0,0,0,0, imageData.width, imageData.height);
// append it to the body
document.body.appendChild(myCanvas);
}
function loadImage(){
var img = new Image();
img.onload = function (){
createCanvas(img);
}
img.src = "monkey.jpg";
}
</script>
</head>
<body onload="loadImage()">
</body>
</html>
The only way you'll be able to do this in JavaScript is with the <canvas> tag. Here is an excellent tutorial if you're interested in learning how to use it.
Edit: I'm not an expert on MS proprietary filters, but here are the Microsoft docs for image filters in IE.