I want to convert paper.js Examples from paperscript to javascript - javascript

I am Japanese and I apologize for my unnatural English, but I would appreciate it if you could read it.
I learned how to convert paperscript to javascript from the official documentation.
Its means are as follows
Change the type attribute of the script tag to text/paperscript. <script type="text/paperscript" src="./main.js"></script>
Enable Paperscope for global use.  paper.install(window)
Specify the target of the canvas. paper.setup(document.getElementById("myCanvas"))
Write the main code in the onload window.onload = function(){ /* add main code */ }
Finally, add paper.view.draw()
The onFrame and onResize transforms as follows. view.onFrame = function(event) {}
onMouseDown, onMouseUp, onMouseDrag, onMouseMove, etc. are converted as follows. var customTool = new Tool(); customTool.onMouseDown = function(event) {};
I have tried these methods, but applying these to the Examples on the paper.js official site does not work correctly.
The following code is the result of trying these.
<!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 type="text/javascript" src="https://unpkg.com/paper"></script>
<script type="text/javascript" src="./main.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function(){
paper.setup(myCanvas)
var points = 25;
// The distance between the points:
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
customTool.onMouseMove=function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
customTool.onMouseDown=function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp=function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
The original paperscript can be found here.
What is the problem with this code?
Thank you for reading to the end!

The var vector in the for loop is not getting the correct values in your code. Change the math operators and it will work like the paperjs demo.
Math operators (+ - * /) for vector only works in paperscript. In Javascript, use .add() .subtract() .multiply() .divide(). see http://paperjs.org/reference/point/#subtract-point
// paperscript
segment.point - nextSegment.point
// javascript
segment.point.subtract(nextSegment.point)
Here's a working demo of your example
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function() {
paper.setup(myCanvas)
var points = 15; //25
// The distance between the points:
var length = 20; //35
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++) {
path.add(start + new Point(i * length, 0));
}
customTool.onMouseMove = function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
//var vector = segment.point - nextSegment.point;
var vector = segment.point.subtract(nextSegment.point);
vector.length = length;
//nextSegment.point = segment.point - vector;
nextSegment.point = segment.point.subtract(vector);
}
path.smooth({
type: 'continuous'
});
}
customTool.onMouseDown = function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp = function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
html,
body {
margin: 0
}
canvas {
border: 1px solid red;
}
<!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 type="text/javascript" src="https://unpkg.com/paper"></script>
<!-- you can add this back in -->
<!-- <script type="text/javascript" src="./main.js"></script> -->
<title>Document</title>
</head>
<body>
<!-- set any size you want, or use CSS/JS to make this resizable -->
<canvas id="myCanvas" width="600" height="150"></canvas>
</body>
</html>

Related

Github Pages as Static Image Hosting

I am trying to use GitHub pages to host static images for a website I am working on. The website randomizes div locations across the page, and it's supposed to use the photos from the repository. Here is the repository that is hosting the images.
The issue is that the images are not loading from the Github pages. Am I not referencing the photos correctly in the Javascript? Here is a photo that shows what the page looks like when I run it. As you can see, none of the images load into the webpage. Not sure if I am referencing the photo incorrectly in the JS, or if I need to add any HTML code to reference the photos. Either way, I would really appreciate any help. :)
HTML:
<!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">
<title>page</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<!-- <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> -->
</head>
<body>
<h1><b>Issy B. Designs</b></h1><br>
<div class="random"></div>
</body>
</html>
JS:
const imgPoss = [];
let maxX, maxY;
function placeImg() {
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const randImg = Math.random() * NUM_OF_IMAGES;
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';
const {random: r} = Math;
const x = r() * maxX;
const y = r() * maxY;
if(!isOverlap(x,y)) {
var link = `<img class="random" style="left: ${x}px; top: ${y}px;" src="${imgSrc}" />`;
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = bodyHtml + link;
imgPoss.push({x, y}); // record all img positions
}
}
function isOverlap(x, y) { // return true if overlapping
const img = {x: 128, y:160};
for(const imgPos of imgPoss) {
if( x>imgPos.x-img.x && x<imgPos.x+img.x &&
y>imgPos.y-img.y && y<imgPos.y+img.y ) return true;
}
return false;
}
onload = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
setInterval(placeImg, 10);
}
onresize = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
}
In JavaScript Math.random() returns float between 0 and 1. By multiplying it by 90 you get a float, but all your photos are intigers. And since your pictures start from 10.png it should look like this
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const START_OF_IMAGES = 10;
const randImg = Math.round(Math.random() * NUM_OF_IMAGES + START_OF_IMAGES);
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';

Paper js stops redrawing after loading another script

I'm using paper js to draw an animated set of rectangles. Since there will be several HTML pages in this project, I tried adding the menu HTML programmatically using javascript. However, once the menu script loads, paper js stops redrawing.
I used a timer to delay the loading of the menu script to ascertain if it was any other issue. The animation definitely plays normally right before the menu script loads.
Any other element added programmatically works fine. It's the only paper that stops redrawing.
HTML
<head>
<script src="./scripts/paper-full.js"></script>
<script type="text/javascript" src="./scripts/menu.js"></script>
<script
type="text/paperscript"
src="./scripts/paper.js"
canvas="myCanvas"
></script>
<!-- <link rel="stylesheet" href="./styles/style.css" /> -->
<link
href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap"
rel="stylesheet"
/>
</head>
<body id="body">
<div id="main">
<label id="stats"></label>
<canvas id="myCanvas" resize></canvas>
</div>
</body>
MENU
var label = '<label id="stats"></label>';
var divO = '<div id="menu" class="menu">';
var divC = "</div>";
var html =
'Home ProjectsBlog About';
setTimeout(() => {
document.body.innerHTML += label + divO + html + divC;
}, 500);
PAPER
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
function onMouseMove(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
function onMouseDown(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
function onMouseUp(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
Your problem comes from the fact that you are resetting the document.body.innerHTML and this somehow breaks Paper.js coupling with the canvas.
What I would suggest is using a dedicated element to insert your dynamic content into the DOM, rather that injecting it into the <body> directly.
Here is an updated code demonstrating the solution. Have a close look at the lines:
<div id="menu-container"></div>
document.querySelector('#menu-container').innerHTML = label + divO + html + divC;
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/paper"></script>
<link
href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap"
rel="stylesheet"
/>
</head>
<body id="body">
<div id="main">
<label id="stats"></label>
<canvas id="myCanvas" resize></canvas>
</div>
<div id="menu-container"></div>
<script type="text/javascript">
var label = '<label id="stats"></label>';
var divO = '<div id="menu" class="menu">';
var divC = "</div>";
var html =
'Home ProjectsBlog About';
document.querySelector('#menu-container').innerHTML = label + divO + html + divC;
</script>
<script type="text/paperscript" canvas="myCanvas">
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var points = 20
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
function onMouseMove(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
function onMouseDown(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
function onMouseUp(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
</script>
</body>
</html>

nvd3 export to img cropping image

im trying to export a NVD3 graph using this tutorials:
http://www.coffeegnome.net/converting-svg-to-png-with-canvg/
SVG to Canvas with d3.js
It works perfectly but my result image is cropped to 300 x 150, how can I export the whole image?
My code is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Export D3 to image</title>
<link rel="stylesheet" type="text/css" href="css/nv.d3.css">
<script language="javascript" type="text/javascript" src="js/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="js/d3.min.js"></script>
<script language="javascript" type="text/javascript" src="js/nv.d3.js"></script>
</head>
<body>
<svg id="basicChart1"></svg>
<script>
createGraphs();
function createGraphs() {
nv.addGraph(function () {
chart1 = nv.models.lineChart()
.useInteractiveGuideline(true)
;
chart1.xAxis
.axisLabel('Time (ms)')
.tickFormat(d3.format(',r'))
;
chart1.yAxis
.axisLabel('Voltage (v)')
.tickFormat(d3.format('.02f'))
;
d3.select('#basicChart1')
.datum(data())
.call(chart1)
;
nv.utils.windowResize(chart1.update);
return chart1;
});
console.log("Graficas Creadas");
}
function data() {
var sin = [];
for (var i = 0; i < 100; i++) {
sin.push({x: i, y: Math.sin(i / 10)});
}
return [
{
values: sin,
key: 'Sine Wave',
color: '#ff7f0e'
}
];
}
// Tutorials:
// http://www.coffeegnome.net/converting-svg-to-png-with-canvg/
// Create an export button
d3.select('body')
.append("button")
.html("Export")
.on("click", saveSVG)
.attr('class', 'btn btn-success');
var width = 300, height = 100;
// Create the export function - this will just export
// the first svg element it finds
function saveSVG() {
// get styles from all required stylesheets
// http://www.coffeegnome.net/converting-svg-to-png-with-canvg/
var style = "\n";
var requiredSheets = ['nv.d3.css']; // list of required CSS
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (sheet.href) {
if (requiredSheets.indexOf(sheet.href.split('/').pop()) !== -1) {
if (sheet.rules) {
for (var j = 0; j < sheet.rules.length; j++) {
style += (sheet.rules[j].cssText + '\n');
}
}
}
}
}
var svg = d3.select("#basicChart1"),
serializer = new XMLSerializer();
// prepend style to svg
svg.insert('defs', ":first-child");
d3.select("svg defs")
.append('style')
.attr('type', 'text/css')
.html(style);
// generate IMG in new tab
var svgStr = serializer.serializeToString(svg.node());
var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgStr)));
var image = new Image();
image.src = imgsrc;
window.open().document.write('<img src="' + image.src + '"/>');
}
;
</script>
</body>
</html>
I'll answer my own question:
The problem was on the SVG Width and Height attributes:
<svg id="basicChart1"></svg>
So i only needed to add the calculated Width and Height values to the svg tag before the generation of the image:
var serializer = new XMLSerializer();
var svg = d3.select("#basicChart1");
svg.attr('width', svg.node().clientWidth);
svg.attr('height', svg.node().clientHeight);
svg.insert('defs', ":first-child");
d3.select("svg defs")
.append('style')
.attr('type', 'text/css')
.html(style);

javascript drawing one more polygon

I want to draw a lot of polygons on a canvas by mouse handlers with pure Javascript language. My project is here.
In my project:
I want to finish draw and create a polygon when I do double click. (I can).
After start a drawing by one click event for make new polygon. (I can't).
When I start new draw adding new point to polygon before maked.
Thank you.
My html file is here:
<html>
<head>
<title>Orhan ALTIN</title>
<meta charset="utf-8">
<style>
canvas{
border: 5px solid;
border-color: rgb(255,173,50);
}
</style>
</head>
<body>
<canvas id="tuval" width="500" height="500"></canvas>
<script>
var tuval = document.getElementById("tuval");
var kaynak = tuval.getContext("2d");
var simdiX=[];
var simdiY=[];
var sonraX=[];
var sonraY=[];
var cizgiler=[];
var cizgi={
x1:0,
y1:0
};
var bas=0;
var fare={
xx:0,
yy:0
};
var cevre=tuval.getBoundingClientRect();
var cizimyap=false;
var yeni=0;
tuval.addEventListener("click",function temizle(olay){
cizimyap=true;
fare={
xx:olay.clientX-cevre.left,
yy:olay.clientY-cevre.top
};
cizgi.x1=fare.xx;
cizgi.y1=fare.yy;
bas=bas+1;
kaynak.moveTo(fare.xx,fare.yy);
bas++;
if(bas>1){
cizgiler.push({
xx1:cizgi.x1,
yy1:cizgi.y1,
xx2:cizgi.x2,
yy2:cizgi.y2
});
}
tuval.addEventListener("mousemove", function oynat(olay){
if (cizimyap) {
kaynak.clearRect(0,0,tuval.width,tuval.height);
kaynak.beginPath();
for (var i = 0, max = cizgiler.length; i < max; i++) {
var dizi=cizgiler[i];
kaynak.moveTo(dizi.xx2,dizi.yy2);
kaynak.lineTo(dizi.xx1,dizi.yy1);
kaynak.stroke();
simdiX.push(dizi.xx1);
simdiY.push(dizi.yy1);
}
kaynak.moveTo(fare.xx,fare.yy);
kaynak.lineTo(olay.clientX-cevre.left,olay.clientY-cevre.top);
kaynak.stroke();
}
});
tuval.addEventListener("dblclick", function(){
cizimyap=false;
poligonYap(olay);
});
});
function poligonYap(olay){
simdiX.splice(simdiX.length-1,1,simdiX[0]);
simdiY.splice(simdiY.length-1,1,simdiY[0]);
kaynak.clearRect(0,0,tuval.width,tuval.height);
for (var i = 0, max = cizgiler.length; i < max; i++) {
//var dizi=cizgiler[i];
kaynak.strokeStyle="green";
kaynak.lineWidth="1";
kaynak.lineCap="round";
sonraX[i]=simdiX[i];
sonraY[i]=simdiY[i];
kaynak.lineTo(sonraX[i],sonraY[i]);
kaynak.stroke();
}
for (var i = 0, max = cizgiler.length-1; i < max; i++) {
kaynak.fillStyle="blue";
kaynak.fillRect(cizgiler[i].xx1-5/2,cizgiler[i].yy1-5/2,5,5);
kaynak.font="12px Tahoma";
kaynak.fillStyle="red";
kaynak.fillText(i+1,cizgiler[i].xx1,cizgiler[i].yy1-5);
}
}
</script>
</body>

HTML5 canvas game static solid elements

I'm writing a canvas game with easeljs. Almost everything is working correctly in this project, only problem is I can't add static objects to the field.
Here is the link my demo: http://insidejs.com/game/
I don't want to enter to the colored areas with shopping cart. Player should turn around these areas. This game illustrates what I need to do.: http://www.kokogames.com/free-games/91/racing-games/138/e-racer.htm
Thanks.
My Project:
<!DOCTYPE html>
<!--[if IE 7]> <html class="no-js ie7"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="tr"><!--<![endif]-->
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Game</title>
<!-- css -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="assets/css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" />
<link href="assets/css/screen.css" rel="stylesheet" type="text/css" />
<!-- css -->
<!-- javascript -->
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/easeljs-0.6.1.min.js"></script>
<script type="text/javascript">
var CANVAS, STAGE, Shopping, GAME;
$(function () {
window.Shopping= {
Game: {}
};
GAME = Shopping.Game;
GAME = new Application();
CANVAS = document.getElementById("game");
STAGE = new createjs.Stage(CANVAS);
GAME.init();
});
var Application = function () {
};
Application.prototype = {
vehicle: null,
vehicleImg: new Image(),
map: null,
mapImg: new Image(),
TURN_FACTOR: 3,
MAX_THRUST: 1,
MAX_VELOCITY: 10,
KEYCODE_UP: 38,
KEYCODE_LEFT: 37,
KEYCODE_RIGHT: 39,
KEYCODE_DOWN: 40,
RIGHT_KEY: false,
LEFT_KEY: false,
UP_KEY: false,
DOWN_KEY: false,
map: null,
init: function () {
GAME.mapImg.src = "assets/images/map.jpg";
GAME.mapImg.name = 'map';
GAME.mapImg.onload = GAME.loadImage();
GAME.vehicleImg.src = "assets/images/vehicle.png";
GAME.vehicleImg.name = 'vehicle';
GAME.vehicleImg.onload = GAME.loadImage();
if (!createjs.Ticker.hasEventListener("tick")) {
createjs.Ticker.addEventListener("tick", GAME.tick);
}
$(document).keydown(GAME.handleKeyDown);
$(document).keyup(GAME.handleKeyUp);
},
loadImage: function () {
GAME.vehicle = new createjs.Bitmap(GAME.vehicleImg);
GAME.vehicle.x = CANVAS.width / 2;
GAME.vehicle.y = CANVAS.height / 2;
GAME.vehicle.width = 100;
GAME.vehicle.height = 69;
GAME.vehicle.regX = GAME.vehicle.width / 2;
GAME.vehicle.regY = GAME.vehicle.height / 2;
GAME.map = new createjs.Bitmap(GAME.mapImg);
GAME.map.scaleX = 1;
GAME.map.scaleY = 1;
GAME.map.width = 3000;
GAME.map.height = 2000;
GAME.map.regX = GAME.map.width / 2;
GAME.map.regY = GAME.map.height / 2;
GAME.map.x = CANVAS.width / 2;
GAME.map.y = CANVAS.height / 2 - 300;
GAME.map.speed = 0;
GAME.map.vX = 0;
GAME.map.vY = 0;
STAGE.addChild(GAME.map);
STAGE.addChild(GAME.vehicle);
STAGE.update();
},
//game listener
tick: function (event) {
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= GAME.TURN_FACTOR;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += GAME.TURN_FACTOR;
}
if (GAME.UP_KEY) {
GAME.accelarate();
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= 5;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += 5;
}
}
if (GAME.DOWN_KEY) {
GAME.decelerate();
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= 5;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += 5;
}
}
STAGE.update(event);
},
handleKeyDown: function (e) {
if (!e) {
var e = window.event;
}
switch (e.keyCode) {
case GAME.KEYCODE_LEFT:
GAME.LEFT_KEY = true;
break;
case GAME.KEYCODE_RIGHT:
GAME.RIGHT_KEY = true;
break;
case GAME.KEYCODE_UP:
e.preventDefault();
GAME.UP_KEY = true;
break;
case GAME.KEYCODE_DOWN:
e.preventDefault();
GAME.DOWN_KEY = true;
break;
}
},
handleKeyUp: function (e) {
if (!e) {
var e = window.event;
}
switch (e.keyCode) {
case GAME.KEYCODE_LEFT:
GAME.LEFT_KEY = false;
break;
case GAME.KEYCODE_RIGHT:
GAME.RIGHT_KEY = false;
break;
case GAME.KEYCODE_UP:
GAME.UP_KEY = false;
break;
case GAME.KEYCODE_DOWN:
GAME.DOWN_KEY = false;
break;
}
},
accelarate: function () {
var angle = GAME.vehicle.rotation;
if (GAME.LEFT_KEY) {
angle -= 5;
}
if (GAME.RIGHT_KEY) {
angle += 5;
}
GAME.map.vX -= Math.cos(angle * Math.PI / 180) * 3;
GAME.map.vY -= Math.sin(angle * Math.PI / 180) * 3;
GAME.map.vX = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vX));
GAME.map.vY = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vY));
GAME.map.x += GAME.map.vX;
GAME.map.y += GAME.map.vY;
},
decelerate: function () {
var angle = GAME.vehicle.rotation;
if (GAME.LEFT_KEY) {
angle -= 5;
}
if (GAME.RIGHT_KEY) {
angle += 5;
}
GAME.map.vX += Math.cos(angle * Math.PI / 180) * 3;
GAME.map.vY += Math.sin(angle * Math.PI / 180) * 3;
GAME.map.vX = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vX));
GAME.map.vY = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vY));
GAME.map.x += GAME.map.vX;
GAME.map.y += GAME.map.vY;
}
//class end
};
</script>
<!-- javascript -->
</head>
<body>
<div id="page">
<canvas id="game" width="640" height="480"></canvas>
</div>
</body>
</html>
To make a collision detection work for your game you will need to make quite some changes to your project:
Currently you have one big JPG as a map, which is not a good idea, if you try to have objects collide with other objects.
1) If you are willing to split up the big JPG map(probably quickest acceptable solution): You can use one big grey JPG als the floor and place single green Bitmaps on top of that floor. Then you can use the Collision Detection suggested by #WiredPrairie (https://github.com/olsn/Collision-Detection-for-EaselJS) - doing the collision check this way should be about 3-4lines of code (+the work of splitting up your current map.jpg).
2) If you want to keep that JPG as map: I suggest you either create custom rectangles for the green areas and check every frame if the shopping cart is inside such a rectangle. Another option would be to implement a physics library like Box2D (I know, this will take some time to get into Box2D or other libraries, and I'm guessing you are looking for a quick solution, but trust me: It'll be worth it)
As a non-related hint: For projects like yours it's really worth taking a look at Box2D or other physic engines, once you get the hang of how it works, it's really a big help to use a physics library ;-)

Categories