The following is a code written in Javascript. It let's me change the appearance of a canvas depending on user input. The question is, how can I make this code more CPU efficient? I ask that because this code is just barely snappy enough on the iPad 2 and any improvement in speed would be really great to have.
With speed I am mainly focusing on that loop that iterates thousands of times (right now 3.600).
function repeat(){
//pc, input_mouse_x/y becomes input x/y.
if(device_type==0){
ix=input_mouse_x;
iy=input_mouse_y;
//if pc's left mouse button isn't clicked then this isn't a valid input.
if(input_mouse_button_left==0) {ix='-';iy='-';}
}
//ipad, input_touch becomes x/y.
if(device_type==1){
ix=input_touch[0][0];
iy=input_touch[0][1];
//iy=trigonometry.flip({'number':iy,'around':screen_center});
iy+=(screen_center-iy)*2;
}
var pencil_x=ix;
var pencil_y=iy; pencil_y+=(screen_center-pencil_y)*2;
var pencil_width=30;
var pencil_height=30;
var data_quantity=(pencil_width*pencil_height*4);
var pencil_width_half=(pencil_width/2);
var pencil_height_half=(pencil_height/2);
var pencil_begin_x=(pencil_x-pencil_width_half);
var pencil_begin_y=(pencil_y-pencil_height_half);
var image_data=drawing_board_canvas_twod.getImageData(pencil_begin_x,pencil_begin_y,pencil_width,pencil_height);
//everything in this loop must be as cpu efficient as possible.
for(var cdata=3;cdata<3600;cdata+=4){
//data to pixel, and then to x/y.
var cpixel=Math.floor(cdata/4);
var cx=(cpixel%pencil_width);
var cy=parseInt(cpixel/pencil_width);
//find distance to center of pencil.
var to_center_x=Math.abs(pencil_width_half-cx);
var to_center_y=Math.abs(pencil_height_half-cy);
var to_center=Math.pow((Math.pow(to_center_x,2)+Math.pow(to_center_y,2)), 0.5);
if(to_center<17){
image_data.data[cdata]=0;//the higher the denser.
}
}
drawing_board_canvas_twod.putImageData(image_data,pencil_begin_x,pencil_begin_y);
}