Sprite not moving on key press - javascript

I am trying to create an endless runner game from scratch using JavaScript, and I am currently in the process of making the character jump. However, when I press the spacebar, my character does not move up, but instead just stays in one place. I have pasted my code below:
let ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 512;
ctx.canvas.width = 512;
// Images
let bg = new Image; // Background
bg.src = "./Background.png";
bg.onload = function() {
ctx.drawImage(bg, 0, 0);
};
let fl = new Image; // Floor
fl.src = "./Floor.png";
fl.onload = function() {
ctx.drawImage(fl, 0, 384);
ctx.drawImage(fl, 128, 384);
ctx.drawImage(fl, 256, 384);
ctx.drawImage(fl, 384, 384);
};
let pl = new Image; // Player
pl.src = "./Idle.png";
pl.onload = function() {
ctx.drawImage(pl, 0, 256);
};
// Movement
let UP = false;
document.onkeydown = function(e) {
if (e.keyCode == 32) UP = true;
};
document.onkeyup = function(e) {
if (e.keyCode == 32) UP = false;
};
setInterval(update, 10);
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Erase previous positions
if (UP) {
pl.onload = function() {
ctx.drawImage(pl, 0, 256 += 1); // Move player up
};
};
};

I fixed it with some help from Rojo.
let ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 512;
ctx.canvas.width = 512;
// Images
let bg = new Image;
bg.src = "./Background.png";
let fl = new Image;
fl.src = "./Floor.png";
let pl = new Image;
pl.src = "./Idle.png";
let y = 256;
pl.onload = function() {
ctx.drawImage(pl, 0, y);
};
let UP = false;
document.onkeydown = function(e) {
if (e.keyCode == 32) UP = true;
};
document.onkeyup = function(e) {
if (e.keyCode == 32) UP = false;
};
function update() {
ctx.clearRect(0, 0, 512, 512);
ctx.drawImage(bg, 0, 0);
ctx.drawImage(fl, 0, 384);
ctx.drawImage(fl, 128, 384);
ctx.drawImage(fl, 256, 384);
ctx.drawImage(fl, 384, 384);
if (UP) {
ctx.drawImage(pl, 0, y -= 1);
} else {
ctx.drawImage(pl, 0, y);
};
};
setInterval(update, 10);

Related

Creating image to draw stuff to it, Then draw the image over canvas

Hello everyone!
Is it possible to create image with JavaScript then render shapes on it, Then draw it to the game canvas?
Without using dataurl, url, or src, on any of that!
var ctx = document.getElementById("canvas").getContext("2d");
var img = new Image();
// TODO: Draw stuff to the image img
function game() {
window.requestAnimationFrame(game);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, 0, 0, 256, 256);
}
window.requestAnimationFrame(game);
The CanvasRenderingContext2D.drawImage() function can take an multiple types of images as a source, including another Canvas. The example below shows that an image is loaded in the first canvas. Then you can draw on it by holding down the mouse and moving it. When you release the second canvas will draw an image of the first canvas as it is at that moment.
And all the magic is just in the last function.
contextTwo.drawImage(canvasOne, 0, 0, 256, 256);
const canvasOne = document.getElementById('canvas1');
const canvasTwo = document.getElementById('canvas2');
const contextOne = canvasOne.getContext('2d');
const contextTwo = canvasTwo.getContext('2d');
canvasOne.width = 256;
canvasOne.height = 256;
canvasTwo.width = 256;
canvasTwo.height = 256;
const canvasBounds = canvasOne.getBoundingClientRect();
let mouseData = {
isClicked: false,
position: [0, 0],
}
const onMouseDown = event => {
mouseData.isClicked = true;
render();
};
const onMouseMove = ({ clientX, clientY }) => {
const x = clientX - canvasBounds.left;
const y = clientY - canvasBounds.top;
mouseData.position = [x, y];
render();
};
const onMouseUp = event => {
mouseData.isClicked = false;
render();
moveImage();
};
function setup() {
const img = new Image();
img.src = '//picsum.photos/256/256'
img.onload = function() {
contextOne.drawImage(img, 0, 0, 256, 256);
}
canvasOne.addEventListener('mousedown', onMouseDown);
canvasOne.addEventListener('mousemove', onMouseMove);
canvasOne.addEventListener('mouseup', onMouseUp);
}
function render() {
requestAnimationFrame(() => {
const { isClicked, position } = mouseData;
const [ x, y ] = position;
if (isClicked) {
contextOne.beginPath();
contextOne.arc(x, y, 5, 0, Math.PI * 2)
contextOne.fillStyle = 'red'
contextOne.fill();
contextOne.closePath();
}
});
}
function moveImage() {
contextTwo.drawImage(canvasOne, 0, 0, 256, 256);
}
setup();
body {
display: flex;
}
canvas {
width: 256px;
height: 256px;
border: 1px solid #d0d0d0;
}
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>

How to set filename while converting canvas to blob?

I want to upload cropped image to server. For this I am using jQuery Jcrop lib in this canvas image cropped then convert to blob that is working perfectly , but the problem is that file name on server is just blob without any extension or undefined type.
When I am using this in img Sec on web page it's working perfectly.
<script>
function uploadPhoto(thisVar) {
if($("#profilePic").val() == "")
{
alert('Please attach a image.');
return false;
}
else
{
var formData = new FormData();
//formData.append("profilePic", $('#profilePic').prop('files')[0])
var blob = dataURLtoBlob(canvas.toDataURL('image/png'));
formData.append("profilePic", blob);
$.ajax({
url:"/imageUpload.jsp",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData:false,
}).done(function(data){
data = $.trim(data);
data = JSON.parse(data);
if(data.status == 'OK'){
alert("Profile pic uploaded successfully.");
$('.imagefldforpar img').attr('src',data.imgPath);
}else{
alert("Profile pic not uploaded.");
}
console.log(data);
$('#uploadPhoto').modal('hide');
});
}
}
</script>
<link href="/css/jquery.Jcrop.min.css" rel="stylesheet">
<script type="text/javascript" src="/js/jquery.Jcrop.min.js"></script>
<script>
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$("#profilePic").change(function() {
loadImage(this);
});
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function(e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
aspectRatio: 4/5,
boxWidth: crop_max_width,
boxHeight: crop_max_height
}, function() {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#cropbutton").click(function(e) {
applyCrop();
});
$("#scalebutton").click(function(e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function(e) {
applyRotate();
});
$("#hflipbutton").click(function(e) {
applyHflip();
});
$("#vflipbutton").click(function(e) {
applyVflip();
});
</script>
Thanks #Zigri2612 for Solution
<script>
function uploadPhoto(thisVar) {
if($("#profilePic").val() == "")
{
alert('Please attach a image.');
return false;
}
else
{
var formData = new FormData();
//formData.append("profilePic", $('#profilePic').prop('files')[0])
var blob = dataURLtoBlob(canvas.toDataURL('image/png'));
formData.append("profilePic", blob,"image.png");
$.ajax({
url:"/imageUpload.jsp",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData:false,
}).done(function(data){
data = $.trim(data);
data = JSON.parse(data);
if(data.status == 'OK'){
alert("Profile pic uploaded successfully.");
$('.imagefldforpar img').attr('src',data.imgPath);
}else{
alert("Profile pic not uploaded.");
}
console.log(data);
$('#uploadPhoto').modal('hide');
});
}
}
</script>
<link href="/css/jquery.Jcrop.min.css" rel="stylesheet">
<script type="text/javascript" src="/js/jquery.Jcrop.min.js"></script>
<script>
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$("#profilePic").change(function() {
loadImage(this);
});
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function(e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
aspectRatio: 4/5,
boxWidth: crop_max_width,
boxHeight: crop_max_height
}, function() {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#cropbutton").click(function(e) {
applyCrop();
});
$("#scalebutton").click(function(e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function(e) {
applyRotate();
});
$("#hflipbutton").click(function(e) {
applyHflip();
});
$("#vflipbutton").click(function(e) {
applyVflip();
});
</script>

Pattern drawings dynamically loaded misbehaving in Safari

Below is provided a script for changing image on click, changes will be affected in canvas.
The script is working properly in Firefox and Chrome but not in Safari
What could be the reason?
<script>
$(function() {
var house = document.getElementById("house");
var ctxHouse = house.getContext("2d");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvas2 = document.getElementById("canvas2");
var ctxHand = canvas2.getContext("2d");
var FabricLink;
var imageObj = new Image();
var red = new Image();
red.onload = function() {
canvas.width = red.width;
canvas.height = red.height;
var houseImage = new Image();
houseImage.onload = function() {
house.width = houseImage.width;
house.height = houseImage.height;
ctxHouse.drawImage(houseImage, 0, 0);
}
houseImage.src = "images/img.jpg";
ctx.drawImage(red, 0, 0);
imageObj.onload = function() {
var pattern = ctx.createPattern(imageObj, 'repeat');
ctx.globalCompositeOperation = 'source-in';
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = pattern;
ctx.fill();
};
$(imageObj).attr('src', 'images/' + FabricLink + '.png');
}
red.src = "images/img.png";
var imageObj2 = new Image();
var blue = new Image();
blue.onload = function() {
canvas2.width = blue.width;
canvas2.height = blue.height;
var houseImage = new Image();
houseImage.onload = function() {
house.width = houseImage.width;
house.height = houseImage.height;
ctxHouse.drawImage(houseImage, 0, 0);
}
houseImage.src = "images/img.jpg";
ctxHand.drawImage(blue, 0, 0);
imageObj2.onload = function() {
var pattern = ctx.createPattern(imageObj2, 'repeat');
ctxHand.globalCompositeOperation = 'source-in';
ctxHand.rect(0, 0, canvas2.width, canvas2.height);
ctxHand.fillStyle = pattern;
ctxHand.fill();
};
$(imageObj2).attr('src', 'images/' + FabricLink + '.png');
}
blue.src = "images/img.png";
$('#style li').click(
function() {
//we get our current filename and use it for the src
var linkIndex = $(this).attr("data-filename");
$(red).attr('src', 'images/' + linkIndex + '.png');
}
);
$('#Sleeves li').click(
function() {
$("#canvas2").addClass("show-z");
//we get our current filename and use it for the src
var SleevesLink = $(this).attr("data-filename");
$(blue).attr('src', 'images/' + SleevesLink + '.png');
}
);
$('#Fabric li').click(
function() {
//we get our current filename and use it for the src
FabricLink = $(this).attr("data-filename");
$(imageObj2).attr('src', 'images/' + FabricLink + '.png');
$(imageObj).attr('src', 'images/' + FabricLink + '.png');
}
);
$("#Fabric li:first-child").click();
}); // end $(function(){});
</script>
While debugging, we could see that imageObj.onload is not getting fired in the first click , only on refresh the change occurs in Safari.
jsfiddle.net/qvfx3kz7 (In the fiddle images are not loading, but the complete code is added)
I am not sure what is exactly the problem with Safari, but what I can see is that you are over-complicating everything by trying to load your assets only when requested, which leads to this callback nightmare you have set up.
Instead, prepare your assets so that you can load it only once. Since you are using patterns, I will assume that each pattern is actually a small image.
So instead of loading every little pattern images, load a single sprite-sheet, which will contain all your patterns.
From there, you'll be able to generate dynamically your CanvasPattern synchronously, without having to care for any loading callback. In order to do this, you will have to use a second, off-screen, canvas, that you will use as he source of createPattern() method:
// really dummy implementation...
function AssetsLoader() {}
AssetsLoader.prototype = Object.create({
addImage: function(objs, cb) {
if (!objs || typeof objs !== 'object') return;
if (!Array.isArray(objs)) objs = [];
var toLoad = objs.length,
imgs = objs.map(loadImage, this);
function loadImage(obj) {
if (!obj.src) return;
this.toLoad++;
var img = new Image();
img.src = obj.src;
img.onload = onimgload;
img.onerror = onimgerror;
return obj.img = img;
}
function onimgload(evt) {
if (--toLoad <= 0 && typeof cb === 'function') cb(imgs);
}
function onimgerror(evt) {
console.warn('failed to load image at ', evt.target.src);
}
}
});
// Some info about our assets, there are an infinity of ways to deal with it,
// You would have to determine yourself what's best for your own case
var dests = {
sofa: {
name: 'sofa',
src: 'https://i.stack.imgur.com/ryO42.png'
},
shirt: {
name: 'shirt',
src: 'https://i.stack.imgur.com/cPNbe.png'
}
};
var patterns = {
name: 'patterns',
src: 'https://i.stack.imgur.com/TdIAJ.png',
positions: {
orange: {
x: 0,
y: 0,
width: 173,
height: 173,
out_width: 75,
out_height: 75
},
violet: {
x: 173,
y: 0,
width: 173,
height: 173,
out_width: 35,
out_height: 35
},
psyche: {
x: 0,
y: 173,
width: 173,
height: 173,
out_width: 25,
out_height: 25
},
pink: {
x: 173,
y: 173,
width: 173,
height: 173,
out_width: 125,
out_height: 125
}
}
}
var assets = new AssetsLoader();
// first load all our images, and only then, start the whole thing
assets.addImage([dests.shirt, dests.sofa, patterns], init);
function init() {
// populate our selects
for (var key in dests) {
dest_select.appendChild(new Option(key, key));
}
for (var key in patterns.positions) {
pat_select.appendChild(new Option(key, key));
}
dest_select.onchange = pat_select.onchange = draw;
var ctx = canvas.getContext('2d');
var offscreenCtx = document.createElement('canvas').getContext('2d');
draw();
function draw() {
var dest = dests[dest_select.value].img;
ctx.canvas.width = dest.width;
ctx.canvas.height = dest.height;
ctx.globalCompositeOperation = 'source-over';
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(dest, 0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'source-in';
// here we generate the CanvasPattern
ctx.fillStyle = getPattern(pat_select.value);
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'luminosity';
ctx.drawImage(dest, 0, 0, canvas.width, canvas.height);
}
// now that we have our patterns loaded in a single sprite-sheet,
// we can generate the CanvasPatterns synchronously
function getPattern(key) {
var pos = patterns.positions[key]; // get our pattern's position in our dictionary
// resize the offscreen canvas so it matches our pattern
offscreenCtx.canvas.width = pos.out_width;
offscreenCtx.canvas.height = pos.out_height;
offscreenCtx.drawImage(patterns.img, pos.x, pos.y, pos.width, pos.height, 0, 0, pos.out_width, pos.out_height);
return offscreenCtx.createPattern(offscreenCtx.canvas, 'repeat');
}
}
<select id="dest_select"></select>
<select id="pat_select"></select>
<br><br><br>
<canvas id="canvas"></canvas>

JCrop: Manipulate image from external URL

I need to rotate/scale/flip/crop an image on an HTML page.
I'm using JCrop.js for image manipulation on client side. I'm able to do this successfully with a file selector, where the user selects an image file on their local computer. My requirement is to do the same, but for an image loaded from another URL (without selecting a local image).
Need help on the next step.
Here is the complete code that works well with local file selection:
HTML:
<img scr="externalURL" id="imgMain" alt=""/>
<input type="button" id="cropbutton" value="Crop" />
<input type="button" id="rotatebutton" value="Rotate" />
<input type="button" id="hflipbutton" value="Flip Horizontal" />
<input type="button" id="vflipbutton" value="Flip Vertical" />
JS:
var cropWidth = 800;
var cropHeight = 800;
var crop_max_width = 400;
var crop_max_height = 400;
var jcrop_api;
var canvas;
var context;
var image;
var prefsize;
$(document).ready(function () {
$("#file").change(function () {
loadImage(this);
});
$("#btnCrop").click(function () {
SaveData();
});
});
function SaveData() {
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob(canvas.toDataURL('image/jpeg'));
formData.append("cropped_image[]", blob, "CroppedImage.jpeg");
$.ajax({
url: urlToSendData
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
alert("Image cropped!");
},
error: function (data) {
alert('There was an error');
}
});
}
function loadImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
canvas = null;
reader.onload = function (e) {
image = new Image();
image.onload = validateImage;
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
applyCrop();
}
}
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
function validateImage() {
if (canvas != null) {
image = new Image();
image.onload = restartJcrop;
image.src = canvas.toDataURL('image/png');
} else restartJcrop();
}
function restartJcrop() {
if (jcrop_api != null) {
jcrop_api.destroy();
}
$("#views").empty();
$("#views").append("<canvas id=\"canvas\">");
canvas = $("#canvas")[0];
context = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
$("#canvas").Jcrop({
onSelect: selectcanvas,
onRelease: clearcanvas,
boxWidth: crop_max_width,
boxHeight: crop_max_height,
allowResize: false,
allowSelect: false,
setSelect: [0, 0, cropWidth, cropHeight],
aspectRatio: 1
}, function () {
jcrop_api = this;
});
clearcanvas();
}
function clearcanvas() {
prefsize = {
x: 0,
y: 0,
w: canvas.width,
h: canvas.height,
};
}
function selectcanvas(coords) {
prefsize = {
x: Math.round(coords.x),
y: Math.round(coords.y),
w: Math.round(coords.w),
h: Math.round(coords.h)
};
}
function applyCrop() {
canvas.width = prefsize.w;
canvas.height = prefsize.h;
context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width - 10, canvas.height - 10);
validateImage();
}
function applyScale(scale) {
if (scale == 1) return;
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
validateImage();
}
function applyRotate() {
canvas.width = image.height;
canvas.height = image.width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.height / 2, image.width / 2);
context.rotate(Math.PI / 2);
context.drawImage(image, -image.width / 2, -image.height / 2);
validateImage();
}
function applyHflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(image.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
validateImage();
}
function applyVflip() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(0, image.height);
context.scale(1, -1);
context.drawImage(image, 0, 0);
validateImage();
}
$("#scalebutton").click(function (e) {
var scale = prompt("Scale Factor:", "1");
applyScale(scale);
});
$("#rotatebutton").click(function (e) {
applyRotate();
});
$("#hflipbutton").click(function (e) {
applyHflip();
});
$("#vflipbutton").click(function (e) {
applyVflip();
});
Looks like loadImage reads the file and sets the image global.
As there is now already an image on the page, we should be able to skip this step.
So we can probably just set the image in ready like this:
$(document).ready(function () {
// (this code replaces the file selecting)
image = $("#imgMain"); // set image from the page
canvas = null; // this was done in loadImage
applyCrop(); // this was called from loadImage
// (this code is the same as before)
$("#btnCrop").click(function () {
SaveData();
});
});

Make drawable field editable with canvas html

I want to resize the canvas field like paint app in javascript how can I do ?
My html file is :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="paint.css">
<title>Paint</title>
</head>
<body>
<canvas id="canvas" style="border: solid 1px black">Your Browser does not support Canvas, please upgrade</canvas>
<script src="paint.js"></script>
</body>
</html>
Thanks !
It turned out to be a bit more complex.
Resizing the canvas clears it, therefore you need to do it this way:
create a new canvas
assign the dimensions
draw the old canvas over the new canvas
replace the old canvas with the new canvas
//Base canvas and dimensions
var canvas = document.body.appendChild(document.createElement("canvas"));
var width = canvas.height = canvas.width = 400;
var height = width;
var ctx = canvas.getContext("2d");
//Drawing variables
var lastPosition = null;
var drawing = false;
//Drawing functionality
function startDraw() {
drawing = true;
}
canvas.onmousedown = startDraw;
function stopDraw() {
drawing = false;
}
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
function mouseMove(evt) {
var pos = {
x: evt.offsetX,
y: evt.offsetY
};
if (lastPosition !== null && drawing === true) {
ctx.beginPath();
ctx.moveTo(lastPosition.x, lastPosition.y);
ctx.lineTo(pos.x, pos.y);
ctx.closePath();
ctx.stroke();
}
lastPosition = pos;
}
canvas.onmousemove = mouseMove;
//Resizer functions
var resizerX = document.body.appendChild(document.createElement("button"));
resizerX.innerHTML = "Resize X";
resizerX.onclick = function() {
var newValue = null;
while (isNaN(newValue) || newValue < 10) {
newValue = parseInt(prompt("Insert new width", width.toString()));
}
var c = document.createElement("canvas");
width = newValue;
c.width = width;
c.height = height;
ctx = c.getContext("2d");
ctx.drawImage(canvas, 0, 0);
canvas.parentNode.replaceChild(c, canvas);
canvas = c;
canvas.onmousedown = startDraw;
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
canvas.onmousemove = mouseMove;
};
var resizerY = document.body.appendChild(document.createElement("button"));
resizerY.innerHTML = "Resize Y";
resizerY.onclick = function() {
var newValue = null;
while (isNaN(newValue) || newValue < 10) {
newValue = parseInt(prompt("Insert new height", height.toString()));
}
var c = document.createElement("canvas");
height = newValue;
c.width = width;
c.height = height;
ctx = c.getContext("2d");
ctx.drawImage(canvas, 0, 0);
canvas.parentNode.replaceChild(c, canvas);
canvas = c;
canvas.onmousedown = startDraw;
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
canvas.onmousemove = mouseMove;
};
canvas {
background-color: #eee
}

Categories